From ee5710f28452cee34088083646ef2a5439a62f32 Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 13:09:29 -0700 Subject: [PATCH 1/8] fromSwagger -> fromSpec --- modules/core/src/main/scala/dev/guardrail/Common.scala | 6 +++--- .../src/main/scala/dev/guardrail/terms/ProtocolTerms.scala | 2 +- .../main/scala/dev/guardrail/terms/client/ClientTerms.scala | 2 +- .../main/scala/dev/guardrail/terms/server/ServerTerms.scala | 2 +- .../asyncHttpClient/AsyncHttpClientClientGenerator.scala | 2 +- .../java/dropwizard/DropwizardServerGenerator.scala | 2 +- .../java/springMvc/SpringMvcClientGenerator.scala | 2 +- .../java/springMvc/SpringMvcServerGenerator.scala | 2 +- .../generators/java/jackson/JacksonGenerator.scala | 4 ++-- .../generators/scala/akkaHttp/AkkaHttpClientGenerator.scala | 2 +- .../generators/scala/akkaHttp/AkkaHttpServerGenerator.scala | 2 +- .../scala/dropwizard/DropwizardClientGenerator.scala | 2 +- .../scala/dropwizard/DropwizardServerGenerator.scala | 2 +- .../generators/scala/http4s/Http4sClientGenerator.scala | 2 +- .../generators/scala/http4s/Http4sServerGenerator.scala | 2 +- .../generators/scala/circe/CirceProtocolGenerator.scala | 4 ++-- .../scala/circe/CirceRefinedProtocolGenerator.scala | 4 ++-- .../generators/scala/jackson/JacksonProtocolGenerator.scala | 4 ++-- .../src/test/scala/tests/circe/ArrayValidationTest.scala | 4 ++-- .../src/test/scala/tests/circe/BigObjectSpec.scala | 2 +- .../src/test/scala/tests/circe/ValidationTest.scala | 2 +- 21 files changed, 28 insertions(+), 28 deletions(-) diff --git a/modules/core/src/main/scala/dev/guardrail/Common.scala b/modules/core/src/main/scala/dev/guardrail/Common.scala index 765d8ca3b4..be596a227b 100644 --- a/modules/core/src/main/scala/dev/guardrail/Common.scala +++ b/modules/core/src/main/scala/dev/guardrail/Common.scala @@ -40,7 +40,7 @@ object Common { import Sw._ Sw.log.function("prepareDefinitions")(for { - proto @ ProtocolDefinitions(protocolElems, protocolImports, packageObjectImports, packageObjectContents, _) <- P.fromSwagger( + proto @ ProtocolDefinitions(protocolElems, protocolImports, packageObjectImports, packageObjectContents, _) <- P.fromSpec( swagger, dtoPackage, supportPackage, @@ -92,14 +92,14 @@ object Common { codegen <- kind match { case CodegenTarget.Client => for { - clientMeta <- C.fromSwagger(context, frameworkImports)(serverUrls, basePath, groupedRoutes)(protocolElems, securitySchemes, components) + clientMeta <- C.fromSpec(context, frameworkImports)(serverUrls, basePath, groupedRoutes)(protocolElems, securitySchemes, components) Clients(clients, supportDefinitions) = clientMeta frameworkImplicits <- getFrameworkImplicits() } yield CodegenDefinitions[L](clients, List.empty, supportDefinitions, frameworkImplicits) case CodegenTarget.Server => for { - serverMeta <- Se.fromSwagger(context, supportPackage, basePath, frameworkImports)(groupedRoutes)(protocolElems, securitySchemes, components) + serverMeta <- Se.fromSpec(context, supportPackage, basePath, frameworkImports)(groupedRoutes)(protocolElems, securitySchemes, components) Servers(servers, supportDefinitions) = serverMeta frameworkImplicits <- getFrameworkImplicits() } yield CodegenDefinitions[L](List.empty, servers, supportDefinitions, frameworkImplicits) diff --git a/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala b/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala index 778f1746c7..436ccab667 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala @@ -17,7 +17,7 @@ abstract class ProtocolTerms[L <: LA, F[_]] { self => def staticProtocolImports(pkgName: List[String]): F[List[L#Import]] def generateSupportDefinitions(): F[List[SupportDefinition[L]]] - def fromSwagger( + def fromSpec( swagger: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], diff --git a/modules/core/src/main/scala/dev/guardrail/terms/client/ClientTerms.scala b/modules/core/src/main/scala/dev/guardrail/terms/client/ClientTerms.scala index e7862f30b3..f0608b70d7 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/client/ClientTerms.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/client/ClientTerms.scala @@ -16,7 +16,7 @@ import java.net.URI abstract class ClientTerms[L <: LA, F[_]] { self => def MonadF: Monad[F] - def fromSwagger(context: Context, frameworkImports: List[L#Import])( + def fromSpec(context: Context, frameworkImports: List[L#Import])( serverUrls: Option[NonEmptyList[URI]], basePath: Option[String], groupedRoutes: List[(List[String], List[RouteMeta])] diff --git a/modules/core/src/main/scala/dev/guardrail/terms/server/ServerTerms.scala b/modules/core/src/main/scala/dev/guardrail/terms/server/ServerTerms.scala index 80134045a2..1a41a4ab3a 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/server/ServerTerms.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/server/ServerTerms.scala @@ -34,7 +34,7 @@ object SecurityExposure { abstract class ServerTerms[L <: LA, F[_]] { self => def MonadF: Monad[F] - def fromSwagger(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[L#Import])( + def fromSpec(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[L#Import])( groupedRoutes: List[(List[String], List[RouteMeta])] )( protocolElems: List[StrictProtocolElems[L]], diff --git a/modules/java-async-http/src/main/scala/dev/guardrail/generators/java/asyncHttpClient/AsyncHttpClientClientGenerator.scala b/modules/java-async-http/src/main/scala/dev/guardrail/generators/java/asyncHttpClient/AsyncHttpClientClientGenerator.scala index 7b5530f224..7a845cf5c4 100644 --- a/modules/java-async-http/src/main/scala/dev/guardrail/generators/java/asyncHttpClient/AsyncHttpClientClientGenerator.scala +++ b/modules/java-async-http/src/main/scala/dev/guardrail/generators/java/asyncHttpClient/AsyncHttpClientClientGenerator.scala @@ -88,7 +88,7 @@ class AsyncHttpClientClientGenerator private (implicit Cl: CollectionsLibTerms[J override implicit def MonadF: Monad[Target] = Target.targetInstances - override def fromSwagger(context: Context, frameworkImports: List[JavaLanguage#Import])( + override def fromSpec(context: Context, frameworkImports: List[JavaLanguage#Import])( serverUrls: Option[NonEmptyList[URI]], basePath: Option[String], groupedRoutes: List[(List[String], List[RouteMeta])] diff --git a/modules/java-dropwizard/src/main/scala/dev/guardrail/generators/java/dropwizard/DropwizardServerGenerator.scala b/modules/java-dropwizard/src/main/scala/dev/guardrail/generators/java/dropwizard/DropwizardServerGenerator.scala index 60fbd2fddd..2f5ef7c6c5 100644 --- a/modules/java-dropwizard/src/main/scala/dev/guardrail/generators/java/dropwizard/DropwizardServerGenerator.scala +++ b/modules/java-dropwizard/src/main/scala/dev/guardrail/generators/java/dropwizard/DropwizardServerGenerator.scala @@ -91,7 +91,7 @@ class DropwizardServerGenerator private (implicit Cl: CollectionsLibTerms[JavaLa override implicit def MonadF: Monad[Target] = Target.targetInstances - override def fromSwagger(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[JavaLanguage#Import])( + override def fromSpec(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[JavaLanguage#Import])( groupedRoutes: List[(List[String], List[RouteMeta])] )( protocolElems: List[StrictProtocolElems[JavaLanguage]], diff --git a/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcClientGenerator.scala b/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcClientGenerator.scala index 0fcdf398b3..07dd5ffca9 100644 --- a/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcClientGenerator.scala +++ b/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcClientGenerator.scala @@ -21,7 +21,7 @@ object SpringMvcClientGenerator { class SpringMvcClientGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, Target]) extends ClientTerms[JavaLanguage, Target] { override def MonadF = Target.targetInstances - override def fromSwagger(context: Context, frameworkImports: List[JavaLanguage#Import])( + override def fromSpec(context: Context, frameworkImports: List[JavaLanguage#Import])( serverUrls: Option[NonEmptyList[URI]], basePath: Option[String], groupedRoutes: List[(List[String], List[RouteMeta])] diff --git a/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcServerGenerator.scala b/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcServerGenerator.scala index 4c8dc60be7..205c954ab7 100644 --- a/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcServerGenerator.scala +++ b/modules/java-spring-mvc/src/main/scala/dev/guardrail/generators/java/springMvc/SpringMvcServerGenerator.scala @@ -90,7 +90,7 @@ class SpringMvcServerGenerator private (implicit Cl: CollectionsLibTerms[JavaLan override implicit def MonadF: Monad[Target] = Target.targetInstances - override def fromSwagger(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[JavaLanguage#Import])( + override def fromSpec(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[JavaLanguage#Import])( groupedRoutes: List[(List[String], List[RouteMeta])] )( protocolElems: List[StrictProtocolElems[JavaLanguage]], diff --git a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala index dd29a710dc..9addfd3f0b 100644 --- a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala +++ b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala @@ -763,7 +763,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T } } - override def fromSwagger( + override def fromSpec( swagger: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], @@ -779,7 +779,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T val components = swagger.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence - Sw.log.function("ProtocolGenerator.fromSwagger")(for { + Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) concreteTypes <- SwaggerUtil.extractConcreteTypes[JavaLanguage, Target](definitions.value, components) diff --git a/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpClientGenerator.scala b/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpClientGenerator.scala index f5d33a8485..b12b62a7b4 100644 --- a/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpClientGenerator.scala +++ b/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpClientGenerator.scala @@ -73,7 +73,7 @@ class AkkaHttpClientGenerator private (modelGeneratorType: ModelGeneratorType) e serverUrls .fold(param"host: String")(v => param"host: String = ${Lit.String(v.head.toString())}") - override def fromSwagger(context: Context, frameworkImports: List[ScalaLanguage#Import])( + override def fromSpec(context: Context, frameworkImports: List[ScalaLanguage#Import])( serverUrls: Option[NonEmptyList[URI]], basePath: Option[String], groupedRoutes: List[(List[String], List[RouteMeta])] diff --git a/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpServerGenerator.scala b/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpServerGenerator.scala index 9c586441aa..01651cb667 100644 --- a/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpServerGenerator.scala +++ b/modules/scala-akka-http/src/main/scala/dev/guardrail/generators/scala/akkaHttp/AkkaHttpServerGenerator.scala @@ -118,7 +118,7 @@ class AkkaHttpServerGenerator private (akkaHttpVersion: AkkaHttpVersion, modelGe implicit def MonadF: Monad[Target] = Target.targetInstances - override def fromSwagger(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[ScalaLanguage#Import])( + override def fromSpec(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[ScalaLanguage#Import])( groupedRoutes: List[(List[String], List[RouteMeta])] )( protocolElems: List[StrictProtocolElems[ScalaLanguage]], diff --git a/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardClientGenerator.scala b/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardClientGenerator.scala index 86fb06aa3b..dbab4e34b1 100644 --- a/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardClientGenerator.scala +++ b/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardClientGenerator.scala @@ -33,7 +33,7 @@ object DropwizardClientGenerator { class DropwizardClientGenerator private extends ClientTerms[ScalaLanguage, Target] { override def MonadF: Monad[Target] = Target.targetInstances - override def fromSwagger(context: Context, frameworkImports: List[ScalaLanguage#Import])( + override def fromSpec(context: Context, frameworkImports: List[ScalaLanguage#Import])( serverUrls: Option[NonEmptyList[URI]], basePath: Option[String], groupedRoutes: List[(List[String], List[RouteMeta])] diff --git a/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardServerGenerator.scala b/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardServerGenerator.scala index afb7b7c8c1..18bbf559db 100644 --- a/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardServerGenerator.scala +++ b/modules/scala-dropwizard/src/main/scala/dev/guardrail/generators/scala/dropwizard/DropwizardServerGenerator.scala @@ -56,7 +56,7 @@ object DropwizardServerGenerator { class DropwizardServerGenerator private extends ServerTerms[ScalaLanguage, Target] { override def MonadF: Monad[Target] = Target.targetInstances - override def fromSwagger(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[ScalaLanguage#Import])( + override def fromSpec(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[ScalaLanguage#Import])( groupedRoutes: List[(List[String], List[RouteMeta])] )( protocolElems: List[StrictProtocolElems[ScalaLanguage]], diff --git a/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sClientGenerator.scala b/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sClientGenerator.scala index ab513221d4..dbc3f75898 100644 --- a/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sClientGenerator.scala +++ b/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sClientGenerator.scala @@ -67,7 +67,7 @@ class Http4sClientGenerator(version: Http4sVersion) extends ClientTerms[ScalaLan serverUrls .fold(param"host: String")(v => param"host: String = ${Lit.String(v.head.toString())}") - override def fromSwagger(context: Context, frameworkImports: List[ScalaLanguage#Import])( + override def fromSpec(context: Context, frameworkImports: List[ScalaLanguage#Import])( serverUrls: Option[NonEmptyList[URI]], basePath: Option[String], groupedRoutes: List[(List[String], List[RouteMeta])] diff --git a/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sServerGenerator.scala b/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sServerGenerator.scala index 043a00478b..e396eb8859 100644 --- a/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sServerGenerator.scala +++ b/modules/scala-http4s/src/main/scala/dev/guardrail/generators/scala/http4s/Http4sServerGenerator.scala @@ -85,7 +85,7 @@ class Http4sServerGenerator private (version: Http4sVersion) extends ServerTerms val authSchemesTypeName: Type.Name = Type.Name("AuthSchemes") val authRequirementTypeName: Type.Name = Type.Name("AuthRequirement") - override def fromSwagger(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[ScalaLanguage#Import])( + override def fromSpec(context: Context, supportPackage: NonEmptyList[String], basePath: Option[String], frameworkImports: List[ScalaLanguage#Import])( groupedRoutes: List[(List[String], List[RouteMeta])] )( protocolElems: List[StrictProtocolElems[ScalaLanguage]], diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala index 9988d8b5ed..9eee4b3ebc 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala @@ -67,7 +67,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa import Target.targetInstances // TODO: Remove me. This resolves implicit ambiguity from MonadChain - override def fromSwagger( + override def fromSpec( swagger: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], @@ -83,7 +83,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa val components = swagger.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence - Sw.log.function("ProtocolGenerator.fromSwagger")(for { + Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) concreteTypes <- SwaggerUtil.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala index 54e3182b04..a0a3eec7cb 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala @@ -137,7 +137,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, import Target.targetInstances // TODO: Remove me. This resolves implicit ambiguity from MonadChain - override def fromSwagger( + override def fromSpec( swagger: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], @@ -153,7 +153,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, val components = swagger.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence - Sw.log.function("ProtocolGenerator.fromSwagger")(for { + Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) concreteTypes <- SwaggerUtil.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala index fcefed7d30..2b2ca0f15f 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala @@ -156,7 +156,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ case _ => param.term.default } - override def fromSwagger( + override def fromSpec( swagger: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], @@ -172,7 +172,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ val components = swagger.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence - Sw.log.function("ProtocolGenerator.fromSwagger")(for { + Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) concreteTypes <- SwaggerUtil.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) diff --git a/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala b/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala index d27c7f2234..f364b454d5 100644 --- a/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala +++ b/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala @@ -93,7 +93,7 @@ class ArrayValidationTest extends AnyFreeSpec with Matchers with SwaggerSpecRunn |""".stripMargin val ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _) = circeProtocolGenerator - .fromSwagger( + .fromSpec( Tracker(swaggerFromString(collectionElementsWithPattern)), dtoPackage = Nil, supportPackage = NonEmptyList.one("foop"), @@ -118,7 +118,7 @@ class ArrayValidationTest extends AnyFreeSpec with Matchers with SwaggerSpecRunn "should generate size boundary constrains" in { val ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _) = circeProtocolGenerator - .fromSwagger( + .fromSpec( Tracker(swaggerFromString(swagger)), dtoPackage = Nil, supportPackage = NonEmptyList.one("foop"), diff --git a/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala b/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala index fc4df29d10..87da36e86b 100644 --- a/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala +++ b/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala @@ -148,7 +148,7 @@ class BigObjectSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { implicit val scalaGenerator = ScalaGenerator() implicit val swaggerGenerator = SwaggerGenerator[ScalaLanguage]() val ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _) = circeProtocolGenerator - .fromSwagger( + .fromSpec( Tracker(swaggerFromString(swagger)), dtoPackage = Nil, supportPackage = NonEmptyList.one("foop"), diff --git a/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala b/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala index 19a910c33c..0a01ebee02 100644 --- a/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala +++ b/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala @@ -68,7 +68,7 @@ class ValidationTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner { implicit val scalaGenerator = ScalaGenerator() implicit val swaggerGenerator = SwaggerGenerator[ScalaLanguage]() val ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _) = circeProtocolGenerator - .fromSwagger( + .fromSpec( Tracker(swaggerFromString(swagger)), dtoPackage = Nil, supportPackage = NonEmptyList.one("foop"), From 39de35aae1340f22694b0aa5bfa7561696475637 Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 13:22:07 -0700 Subject: [PATCH 2/8] Rename swagger to "spec" broadly --- .../src/main/scala/dev/guardrail/Common.scala | 20 ++++++------- .../{ReadSwagger.scala => ReadSpec.scala} | 6 ++-- .../scala/dev/guardrail/SwaggerUtil.scala | 4 +-- .../dev/guardrail/core/CoreTermInterp.scala | 10 +++---- .../scala/dev/guardrail/core/Tracker.scala | 2 +- .../generators/spi/CoreTermsLoader.scala | 6 ++-- .../guardrail/runner/GuardrailRunner.scala | 6 ++-- .../runner/GuardrailRunnerCompat.scala | 4 +-- .../scala/dev/guardrail/terms/CoreTerms.scala | 4 +-- .../dev/guardrail/terms/ProtocolTerms.scala | 2 +- .../dev/guardrail/terms/SwaggerTerms.scala | 2 +- .../scala/support/SwaggerSpecRunner.scala | 8 +++--- .../server/DropwizardContentTypesTest.scala | 6 ++-- .../java/jackson/JacksonGenerator.scala | 12 ++++---- .../src/test/scala/core/issues/Issue105.scala | 4 +-- .../src/test/scala/core/issues/Issue122.scala | 4 +-- .../src/test/scala/core/issues/Issue126.scala | 4 +-- .../src/test/scala/core/issues/Issue127.scala | 4 +-- .../src/test/scala/core/issues/Issue145.scala | 6 ++-- .../test/scala/core/issues/Issue1682.scala | 4 +-- .../src/test/scala/core/issues/Issue313.scala | 4 +-- .../src/test/scala/core/issues/Issue43.scala | 28 +++++++++---------- .../src/test/scala/core/issues/Issue61.scala | 6 ++-- .../AkkaHttpClientGeneratorTest.scala | 6 ++-- .../akkaHttp/AkkaHttpServerTest.scala | 8 +++--- .../akkaHttp/CustomHeaderTest.scala | 4 +-- .../generators/akkaHttp/DefinitionSpec.scala | 10 +++---- .../tests/generators/akkaHttp/EnumTest.scala | 6 ++-- .../akkaHttp/PropertyExtractors.scala | 4 +-- .../akkaHttp/StaticParametersTest.scala | 4 +-- .../client/AkkaHttpClientTracingTest.scala | 8 +++--- .../akkaHttp/client/BasicTest.scala | 8 +++--- .../client/DefaultParametersTest.scala | 4 +-- .../akkaHttp/client/FormFieldsTest.scala | 4 +-- .../akkaHttp/client/HardcodedQSSpec.scala | 4 +-- .../akkaHttp/client/HttpBodiesTest.scala | 4 +-- .../akkaHttp/client/MultipartTest.scala | 4 +-- .../akkaHttp/client/ParamConflictsTest.scala | 6 ++-- .../akkaHttp/client/SchemeTest.scala | 4 +-- .../client/contentType/TextPlainTest.scala | 4 +-- .../akkaHttp/server/FormFieldsTest.scala | 4 +-- .../src/test/scala/core/issues/Issue144.scala | 4 +-- .../src/test/scala/core/issues/Issue165.scala | 4 +-- .../src/test/scala/core/issues/Issue166.scala | 4 +-- .../test/scala/core/issues/Issue1682.scala | 4 +-- .../src/test/scala/core/issues/Issue222.scala | 8 +++--- .../src/test/scala/core/issues/Issue223.scala | 4 +-- .../src/test/scala/core/issues/Issue225.scala | 4 +-- .../src/test/scala/core/issues/Issue255.scala | 4 +-- .../src/test/scala/core/issues/Issue260.scala | 4 +-- .../src/test/scala/core/issues/Issue370.scala | 4 +-- .../src/test/scala/core/issues/Issue416.scala | 4 +-- .../src/test/scala/core/issues/Issue420.scala | 4 +-- .../src/test/scala/core/issues/Issue429.scala | 4 +-- .../src/test/scala/core/issues/Issue538.scala | 16 +++++------ .../tests/core/FullyQualifiedNames.scala | 4 +-- .../tests/generators/http4s/BasicTest.scala | 8 +++--- .../generators/http4s/Http4sServerTest.scala | 8 +++--- .../http4s/client/DefaultParametersTest.scala | 4 +-- .../scala/circe/CirceProtocolGenerator.scala | 12 ++++---- .../circe/CirceRefinedProtocolGenerator.scala | 12 ++++---- .../jackson/JacksonProtocolGenerator.scala | 12 ++++---- .../tests/circe/ArrayValidationTest.scala | 4 +-- .../scala/tests/circe/BigObjectSpec.scala | 4 +-- .../scala/tests/circe/ValidationTest.scala | 4 +-- src/test/scala/codegen/WritePackageSpec.scala | 8 +++--- .../scala/swagger/VendorExtensionTest.scala | 2 +- src/test/scala/tests/core/BacktickTest.scala | 8 +++--- .../tests/core/DereferencingAliasesSpec.scala | 4 +-- .../scala/tests/core/ScalaTypesTest.scala | 4 +-- src/test/scala/tests/core/TrackerTests.scala | 8 +++--- src/test/scala/tests/core/TypesTest.scala | 20 ++++++------- 72 files changed, 225 insertions(+), 225 deletions(-) rename modules/core/src/main/scala/dev/guardrail/{ReadSwagger.scala => ReadSpec.scala} (85%) diff --git a/modules/core/src/main/scala/dev/guardrail/Common.scala b/modules/core/src/main/scala/dev/guardrail/Common.scala index be596a227b..f02ac81cb9 100644 --- a/modules/core/src/main/scala/dev/guardrail/Common.scala +++ b/modules/core/src/main/scala/dev/guardrail/Common.scala @@ -24,7 +24,7 @@ object Common { def prepareDefinitions[L <: LA, F[_]]( kind: CodegenTarget, context: Context, - swagger: Tracker[OpenAPI], + spec: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String] )(implicit @@ -41,14 +41,14 @@ object Common { Sw.log.function("prepareDefinitions")(for { proto @ ProtocolDefinitions(protocolElems, protocolImports, packageObjectImports, packageObjectContents, _) <- P.fromSpec( - swagger, + spec, dtoPackage, supportPackage, context.propertyRequirement ) serverUrls = NonEmptyList.fromList( - swagger + spec .downField("servers", _.getServers) .flatExtract(server => server @@ -66,7 +66,7 @@ object Common { .toList ) ) - basePath = swagger + basePath = spec .downField("servers", _.getServers) .cotraverse(_.downField("url", _.getUrl)) .headOption @@ -74,15 +74,15 @@ object Common { .flatMap(url => Option(new URI(url).getPath)) .filter(_ != "/") - paths = swagger.downField("paths", _.getPaths) + paths = spec.downField("paths", _.getPaths) globalSecurityRequirements = NonEmptyList - .fromList(swagger.downField("security", _.getSecurity).indexedDistribute) + .fromList(spec.downField("security", _.getSecurity).indexedDistribute) .flatMap(SecurityRequirements(_, SecurityRequirements.Global)) - components = swagger.downField("components", _.getComponents) + components = spec.downField("components", _.getComponents) requestBodies <- extractCommonRequestBodies(components) routes <- extractOperations(paths, requestBodies, globalSecurityRequirements) prefixes <- Cl.vendorPrefixes() - securitySchemes <- SwaggerUtil.extractSecuritySchemes(swagger.unwrapTracker, prefixes) + securitySchemes <- SwaggerUtil.extractSecuritySchemes(spec.unwrapTracker, prefixes) classNamedRoutes <- routes.traverse(route => getClassName(route.operation, prefixes, context.tagsBehaviour).map(_ -> route)) groupedRoutes = classNamedRoutes .groupMap(_._1)(_._2) @@ -198,7 +198,7 @@ object Common { def processArgs[L <: LA, F[_]]( args: NonEmptyList[Args] - )(implicit C: CoreTerms[L, F]): F[NonEmptyList[ReadSwagger[Target[List[WriteTree]]]]] = { + )(implicit C: CoreTerms[L, F]): F[NonEmptyList[ReadSpec[Target[List[WriteTree]]]]] = { import C._ args.traverse(arg => for { @@ -211,7 +211,7 @@ object Common { def runM[L <: LA, F[_]]( args: NonEmptyList[Args] - )(implicit C: CoreTerms[L, F]): F[NonEmptyList[ReadSwagger[Target[List[WriteTree]]]]] = { + )(implicit C: CoreTerms[L, F]): F[NonEmptyList[ReadSpec[Target[List[WriteTree]]]]] = { import C._ for { diff --git a/modules/core/src/main/scala/dev/guardrail/ReadSwagger.scala b/modules/core/src/main/scala/dev/guardrail/ReadSpec.scala similarity index 85% rename from modules/core/src/main/scala/dev/guardrail/ReadSwagger.scala rename to modules/core/src/main/scala/dev/guardrail/ReadSpec.scala index 5cc9a3d464..c28528977a 100644 --- a/modules/core/src/main/scala/dev/guardrail/ReadSwagger.scala +++ b/modules/core/src/main/scala/dev/guardrail/ReadSpec.scala @@ -9,9 +9,9 @@ import io.swagger.parser.OpenAPIParser import io.swagger.v3.oas.models.OpenAPI import io.swagger.v3.parser.core.models.ParseOptions -case class ReadSwagger[T](path: Path, next: OpenAPI => T) -object ReadSwagger { - def readSwagger[T](rs: ReadSwagger[Target[T]]): Target[T] = +case class ReadSpec[T](path: Path, next: OpenAPI => T) +object ReadSpec { + def readSwagger[T](rs: ReadSpec[Target[T]]): Target[T] = if (rs.path.toFile.exists()) { val opts = new ParseOptions() opts.setResolve(true) diff --git a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala index dffa4e366c..86017efe5a 100644 --- a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala +++ b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala @@ -378,13 +378,13 @@ object SwaggerUtil { } def extractSecuritySchemes[L <: LA, F[_]]( - swagger: OpenAPI, + spec: OpenAPI, prefixes: List[String] )(implicit Sw: SwaggerTerms[L, F], Sc: LanguageTerms[L, F]): F[Map[String, SecurityScheme[L]]] = { import Sw._ import Sc._ - Tracker(swagger) + Tracker(spec) .downField("components", _.getComponents) .flatDownField("securitySchemes", _.getSecuritySchemes) .indexedDistribute diff --git a/modules/core/src/main/scala/dev/guardrail/core/CoreTermInterp.scala b/modules/core/src/main/scala/dev/guardrail/core/CoreTermInterp.scala index 00b8310c77..724690d6e2 100644 --- a/modules/core/src/main/scala/dev/guardrail/core/CoreTermInterp.scala +++ b/modules/core/src/main/scala/dev/guardrail/core/CoreTermInterp.scala @@ -14,7 +14,7 @@ import dev.guardrail.MissingArg import dev.guardrail.NoArgsSpecified import dev.guardrail.NoFramework import dev.guardrail.PrintHelp -import dev.guardrail.ReadSwagger +import dev.guardrail.ReadSpec import dev.guardrail.Target import dev.guardrail.UnparseableArgument import dev.guardrail.WriteTree @@ -100,7 +100,7 @@ class CoreTermInterp[L <: LA]( } } - def processArgSet(targetInterpreter: Framework[L, Target])(args: Args): Target[ReadSwagger[Target[List[WriteTree]]]] = + def processArgSet(targetInterpreter: Framework[L, Target])(args: Args): Target[ReadSpec[Target[List[WriteTree]]]] = Target.log.function("processArgSet")( for { _ <- Target.log.debug("Processing arguments") @@ -119,9 +119,9 @@ class CoreTermInterp[L <: LA]( } yield customImport ) _ <- Target.log.debug("Finished processing arguments") - } yield ReadSwagger( + } yield ReadSpec( Paths.get(specPath), - swagger => + spec => try { import targetInterpreter._ val Sw = implicitly[SwaggerTerms[L, Target]] @@ -135,7 +135,7 @@ class CoreTermInterp[L <: LA]( .prepareDefinitions[L, Target]( kind, context, - Tracker(swagger), + Tracker(spec), definitionsPkgName.toList ++ ("definitions" :: dtoPackage), definitionsPkgName :+ "support" ) diff --git a/modules/core/src/main/scala/dev/guardrail/core/Tracker.scala b/modules/core/src/main/scala/dev/guardrail/core/Tracker.scala index 66e7ec1a76..8f2bee7fe4 100644 --- a/modules/core/src/main/scala/dev/guardrail/core/Tracker.scala +++ b/modules/core/src/main/scala/dev/guardrail/core/Tracker.scala @@ -154,7 +154,7 @@ object Tracker extends HighPriorityTrackerEvidence with HighPriorityTrackerSynta def apply(a: A): B } - def apply(swagger: OpenAPI): Tracker[OpenAPI] = new Tracker(swagger, Vector.empty) + def apply(spec: OpenAPI): Tracker[OpenAPI] = new Tracker(spec, Vector.empty) def cloneHistory[A, B](tracker: Tracker[A], value: B): Tracker[B] = new Tracker(value, tracker.history) def unapply[A](instance: Tracker[A]): Some[(String, A)] = Some((instance.showHistory, instance.unwrapTracker)) } diff --git a/modules/core/src/main/scala/dev/guardrail/generators/spi/CoreTermsLoader.scala b/modules/core/src/main/scala/dev/guardrail/generators/spi/CoreTermsLoader.scala index 5c51135c52..d00ec0cbae 100644 --- a/modules/core/src/main/scala/dev/guardrail/generators/spi/CoreTermsLoader.scala +++ b/modules/core/src/main/scala/dev/guardrail/generators/spi/CoreTermsLoader.scala @@ -3,20 +3,20 @@ package dev.guardrail.generators.spi import cats.data.NonEmptyList import dev.guardrail.languages.LA import dev.guardrail.terms.CoreTerms -import dev.guardrail.{ Args, Common, MissingDependency, ReadSwagger, Target, WriteTree } +import dev.guardrail.{ Args, Common, MissingDependency, ReadSpec, Target, WriteTree } import java.util.ServiceLoader import scala.jdk.CollectionConverters._ trait CoreTermsLoader { def runM[L <: LA](parameters: NonEmptyList[Args])(implicit ct: CoreTerms[L, Target]) = Common.runM[L, Target](parameters) - def apply(language: String, parameters: NonEmptyList[Args]): Option[Function0[Target[NonEmptyList[ReadSwagger[Target[List[WriteTree]]]]]]] + def apply(language: String, parameters: NonEmptyList[Args]): Option[Function0[Target[NonEmptyList[ReadSpec[Target[List[WriteTree]]]]]]] } object CoreTermsLoader { @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) def loader: ServiceLoader[CoreTermsLoader] = ServiceLoader.load(classOf[CoreTermsLoader]) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) - def load(language: String, parameters: NonEmptyList[Args], error: MissingDependency): Target[NonEmptyList[ReadSwagger[Target[List[WriteTree]]]]] = { + def load(language: String, parameters: NonEmptyList[Args], error: MissingDependency): Target[NonEmptyList[ReadSpec[Target[List[WriteTree]]]]] = { val found = loader .iterator() .asScala diff --git a/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunner.scala b/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunner.scala index ffd2fa8e42..ce1e90fe8b 100644 --- a/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunner.scala +++ b/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunner.scala @@ -5,7 +5,7 @@ import cats.data.NonEmptyList import cats.syntax.all._ import scala.io.AnsiColor -import dev.guardrail.{ Args, MissingDependency, ReadSwagger, Target, WriteTree } +import dev.guardrail.{ Args, MissingDependency, ReadSpec, Target, WriteTree } import dev.guardrail.core.StructuredLogger import dev.guardrail.generators.spi.CoreTermsLoader @@ -14,7 +14,7 @@ trait GuardrailRunner { runLanguages(tasks) .flatMap( _.flatTraverse(rs => - ReadSwagger + ReadSpec .readSwagger(rs) .flatMap(_.traverse(WriteTree.writeTree)) .leftFlatMap(value => @@ -26,7 +26,7 @@ trait GuardrailRunner { .map(_.distinct) } - def runLanguages(tasks: Map[String, NonEmptyList[Args]]): Target[List[ReadSwagger[Target[List[WriteTree]]]]] = + def runLanguages(tasks: Map[String, NonEmptyList[Args]]): Target[List[ReadSpec[Target[List[WriteTree]]]]] = tasks.toList.flatTraverse { case (language, args) => CoreTermsLoader .load(language, args, MissingDependency(s"${language}-support")) diff --git a/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunnerCompat.scala b/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunnerCompat.scala index d0f3bfcb24..78d14407e5 100644 --- a/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunnerCompat.scala +++ b/modules/core/src/main/scala/dev/guardrail/runner/GuardrailRunnerCompat.scala @@ -2,7 +2,7 @@ package dev.guardrail.runner import cats.data.NonEmptyList -import dev.guardrail.{ Args, ReadSwagger, Target, WriteTree } +import dev.guardrail.{ Args, ReadSpec, Target, WriteTree } -abstract class GuardrailRunnerCompat(val languages: Map[String, NonEmptyList[Args] => Target[NonEmptyList[ReadSwagger[Target[List[WriteTree]]]]]]) +abstract class GuardrailRunnerCompat(val languages: Map[String, NonEmptyList[Args] => Target[NonEmptyList[ReadSpec[Target[List[WriteTree]]]]]]) extends GuardrailRunner diff --git a/modules/core/src/main/scala/dev/guardrail/terms/CoreTerms.scala b/modules/core/src/main/scala/dev/guardrail/terms/CoreTerms.scala index ca84870570..f50ff0acd0 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/CoreTerms.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/CoreTerms.scala @@ -11,13 +11,13 @@ abstract class CoreTerms[L <: LA, F[_]] { self => def getDefaultFramework: F[Option[String]] def extractGenerator(context: Context, defaultFramework: Option[String]): F[Framework[L, Target]] def validateArgs(parsed: List[Args]): F[NonEmptyList[Args]] - def processArgSet(targetInterpreter: Framework[L, Target])(args: Args): F[ReadSwagger[Target[List[WriteTree]]]] + def processArgSet(targetInterpreter: Framework[L, Target])(args: Args): F[ReadSpec[Target[List[WriteTree]]]] def copy( MonadF: Monad[F] = self.MonadF, getDefaultFramework: F[Option[String]] = self.getDefaultFramework, extractGenerator: (Context, Option[String]) => F[Framework[L, Target]] = self.extractGenerator _, validateArgs: List[Args] => F[NonEmptyList[Args]] = self.validateArgs _, - processArgSet: Framework[L, Target] => Args => F[ReadSwagger[Target[List[WriteTree]]]] = self.processArgSet _ + processArgSet: Framework[L, Target] => Args => F[ReadSpec[Target[List[WriteTree]]]] = self.processArgSet _ ) = { val newMonadF = MonadF val newGetDefaultFramework = getDefaultFramework diff --git a/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala b/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala index 436ccab667..793a6861ab 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/ProtocolTerms.scala @@ -18,7 +18,7 @@ abstract class ProtocolTerms[L <: LA, F[_]] { self => def generateSupportDefinitions(): F[List[SupportDefinition[L]]] def fromSpec( - swagger: Tracker[OpenAPI], + spec: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], defaultPropertyRequirement: PropertyRequirement diff --git a/modules/core/src/main/scala/dev/guardrail/terms/SwaggerTerms.scala b/modules/core/src/main/scala/dev/guardrail/terms/SwaggerTerms.scala index 64f8a7b510..59d8db1363 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/SwaggerTerms.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/SwaggerTerms.scala @@ -32,7 +32,7 @@ abstract class SwaggerTerms[L <: LA, F[_]] { def MonadF: Monad[F] def extractCommonRequestBodies(components: Tracker[Option[Components]]): F[Map[String, RequestBody]] - def extractEnum(swagger: Tracker[EnumSchema]): F[Either[String, HeldEnum]] + def extractEnum(spec: Tracker[EnumSchema]): F[Either[String, HeldEnum]] def extractOperations( paths: Tracker[Mappish[List, String, PathItem]], commonRequestBodies: Map[String, RequestBody], diff --git a/modules/core/src/test/scala/support/SwaggerSpecRunner.scala b/modules/core/src/test/scala/support/SwaggerSpecRunner.scala index ed57f2b76a..dcd33704fb 100644 --- a/modules/core/src/test/scala/support/SwaggerSpecRunner.scala +++ b/modules/core/src/test/scala/support/SwaggerSpecRunner.scala @@ -66,7 +66,7 @@ trait SwaggerSpecRunner extends EitherValues with OptionValues with TargetValues } private def runSwagger[L <: LA]( - swagger: OpenAPI, + spec: OpenAPI, dtoPackage: List[String], supportPackage: NonEmptyList[String] )(context: Context, framework: Framework[L, Target], targets: NonEmptyList[CodegenTarget]): (ProtocolDefinitions[L], Clients[L], Servers[L]) = { @@ -77,7 +77,7 @@ trait SwaggerSpecRunner extends EitherValues with OptionValues with TargetValues .prepareDefinitions[L, Target]( target, context, - Tracker(swagger), + Tracker(spec), dtoPackage, supportPackage ) @@ -118,14 +118,14 @@ trait SwaggerSpecRunner extends EitherValues with OptionValues with TargetValues } private def runInvalidSwagger[L <: LA]( - swagger: OpenAPI + spec: OpenAPI )(context: Context, kind: CodegenTarget, framework: Framework[L, Target]): (StructuredLogger, Error) = { import framework._ Common .prepareDefinitions[L, Target]( kind, context, - Tracker(swagger), + Tracker(spec), List.empty, NonEmptyList.one("support") ) match { diff --git a/modules/java-dropwizard/src/test/scala/tests/generators/dropwizard/server/DropwizardContentTypesTest.scala b/modules/java-dropwizard/src/test/scala/tests/generators/dropwizard/server/DropwizardContentTypesTest.scala index 3001aa922e..23f59573c2 100644 --- a/modules/java-dropwizard/src/test/scala/tests/generators/dropwizard/server/DropwizardContentTypesTest.scala +++ b/modules/java-dropwizard/src/test/scala/tests/generators/dropwizard/server/DropwizardContentTypesTest.scala @@ -11,7 +11,7 @@ import scala.compat.java8.OptionConverters._ import support.SwaggerSpecRunner class DropwizardContentTypesTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner { - private val swagger: String = + private val spec: String = s""" |openapi: 3.0.1 |paths: @@ -46,7 +46,7 @@ class DropwizardContentTypesTest extends AnyFreeSpec with Matchers with SwaggerS _, _, Servers(Server(_, _, _, genResource :: Nil) :: Nil, _) - ) = runSwaggerSpec(javaInterpreter)(swagger)(Context.empty, "dropwizard") + ) = runSwaggerSpec(javaInterpreter)(spec)(Context.empty, "dropwizard") genResource .asClassOrInterfaceDeclaration() @@ -72,7 +72,7 @@ class DropwizardContentTypesTest extends AnyFreeSpec with Matchers with SwaggerS _, _, Servers(Server(_, _, _, genResource :: Nil) :: Nil, _) - ) = runSwaggerSpec(javaInterpreter)(swagger)(Context.empty, "dropwizard") + ) = runSwaggerSpec(javaInterpreter)(spec)(Context.empty, "dropwizard") val annotationArrayValues = genResource .asClassOrInterfaceDeclaration() diff --git a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala index 9addfd3f0b..97c761bc26 100644 --- a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala +++ b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala @@ -764,7 +764,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T } override def fromSpec( - swagger: Tracker[OpenAPI], + spec: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], defaultPropertyRequirement: PropertyRequirement @@ -777,7 +777,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T ): Target[ProtocolDefinitions[JavaLanguage]] = { import Sc._ - val components = swagger.downField("components", _.getComponents()) + val components = spec.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) @@ -1636,8 +1636,8 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T } yield dtoClass } - private def extractProperties(swagger: Tracker[Schema[_]]) = - swagger + private def extractProperties(spec: Tracker[Schema[_]]) = + spec .refine[Target[List[(String, Tracker[Schema[_]])]]] { case m: ObjectSchema => m }(m => Target.pure(m.downField("properties", _.getProperties()).indexedCosequence.value) ) @@ -1925,7 +1925,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T } private def extractSuperClass( - swagger: Tracker[ComposedSchema], + spec: Tracker[ComposedSchema], definitions: List[(String, Tracker[Schema[_]])] ) = { def allParents(model: Tracker[Schema[_]]): List[(String, Tracker[Schema[_]], List[Tracker[Schema[_]]])] = @@ -1943,7 +1943,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T ) .getOrElse(List.empty) - Target.pure(allParents(swagger)) + Target.pure(allParents(spec)) } private def renderADTStaticDefns( diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue105.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue105.scala index 1e882edd29..ed89b0ea28 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue105.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue105.scala @@ -13,7 +13,7 @@ import dev.guardrail.generators.scala.syntax.companionForStaticDefns import dev.guardrail.terms.protocol.ClassDefinition class Issue105 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -40,7 +40,7 @@ class Issue105 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue122.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue122.scala index 71d4929389..a9a768882b 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue122.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue122.scala @@ -11,7 +11,7 @@ import dev.guardrail.generators.scala.syntax.companionForStaticDefns import dev.guardrail.generators.{ Client, Clients } class Issue122 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -56,7 +56,7 @@ class Issue122 extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, imports, staticDefns, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val client = q""" diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue126.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue126.scala index 10ea7f04ca..9a8d83d2c9 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue126.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue126.scala @@ -10,7 +10,7 @@ import org.scalatest.matchers.should.Matchers class Issue126 extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = s""" + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io |paths: @@ -28,7 +28,7 @@ class Issue126 extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, _, Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val handler = q""" trait StoreHandler { diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue127.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue127.scala index b9716a3413..d954781aab 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue127.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue127.scala @@ -10,7 +10,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class Issue127 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: '2.0' |host: localhost:1234 |schemes: @@ -37,7 +37,7 @@ class Issue127 extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, _, Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val handler = q""" trait Handler { diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue145.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue145.scala index a60a034089..b7f929387b 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue145.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue145.scala @@ -16,8 +16,8 @@ class Issue145 extends AnyFunSpec with Matchers with SwaggerSpecRunner { describe("Generate hierarchical classes") { - val swagger: String = """ - | swagger: '2.0' + val spec: String = """ + | spec: '2.0' | info: | title: Parsing Error Sample | version: 1.0.0 @@ -49,7 +49,7 @@ class Issue145 extends AnyFunSpec with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") it("should generate right companion object") { val cmp = companionForStaticDefns(staticDefnsPet) diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue1682.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue1682.scala index 506e8e8616..2e57c8c0b4 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue1682.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue1682.scala @@ -8,7 +8,7 @@ import org.scalatest.matchers.should.Matchers class Issue1682 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io |paths: @@ -31,6 +31,6 @@ class Issue1682 extends AnyFunSuite with Matchers with SwaggerSpecRunner { |""".stripMargin test("Support for HTTP HEAD method") { - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") } } diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue313.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue313.scala index 3c7235ee71..26d93f77df 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue313.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue313.scala @@ -12,7 +12,7 @@ import support.SwaggerSpecRunner import scala.meta._ class Issue313 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |openapi: 3.0.2 |info: | title: Whatever @@ -50,7 +50,7 @@ class Issue313 extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, imports, staticDefns, NonEmptyList(Right(cls), _), _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val client = q""" diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue43.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue43.scala index 7d91e4a115..5296085c07 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue43.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue43.scala @@ -16,8 +16,8 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { describe("Generate hierarchical classes") { - val swagger: String = """ - | swagger: '2.0' + val spec: String = """ + | spec: '2.0' | info: | title: Parsing Error Sample | version: 1.0.0 @@ -99,7 +99,7 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val companion = companionForStaticDefns(staticDefns) val companionCat = companionForStaticDefns(staticDefnsCat) @@ -189,8 +189,8 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { describe("Generate deep hierarchical classes") { - val swagger: String = """ - | swagger: '2.0' + val spec: String = """ + | spec: '2.0' | info: | title: Parsing Error Sample | version: 1.0.0 @@ -278,7 +278,7 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val companionPersianCat = companionForStaticDefns(staticDefnsPersianCat) val companionDog = companionForStaticDefns(staticDefnsDog) val companionPet = companionForStaticDefns(staticDefnsPet) @@ -388,7 +388,7 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { } describe("Generate hierarchical classes with empty properties") { - val swagger: String = """ + val spec: String = """ |swagger: '2.0' |info: | title: Parsing Error Sample @@ -415,7 +415,7 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(cls, _, _, defCls, _, _) :: ADT(_, _, _, _, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") it("Direct extension should be supported") { cls shouldBe "Cat" @@ -425,8 +425,8 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { describe("Only first discriminator should be used. Other should be ignored.") { - val swagger: String = """ - | swagger: '2.0' + val spec: String = """ + | spec: '2.0' | info: | title: Parsing Error Sample | version: 1.0.0 @@ -475,7 +475,7 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val companionPersianCat = companionForStaticDefns(staticDefnsPersianCat) val companionCat = companionForStaticDefns(staticDefnsCat) @@ -524,9 +524,9 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { describe("Support multiple inheritance.") { - val swagger: String = + val spec: String = """ - | swagger: '2.0' + | spec: '2.0' | info: | title: Parsing Error Sample | version: 1.0.0 @@ -574,7 +574,7 @@ class Issue43 extends AnyFunSpec with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val companionCat = companionForStaticDefns(staticDefnsCat) val companionPet = companionForStaticDefns(staticDefnsPet) val companionMammal = companionForStaticDefns(staticDefnsMammal) diff --git a/modules/scala-akka-http/src/test/scala/core/issues/Issue61.scala b/modules/scala-akka-http/src/test/scala/core/issues/Issue61.scala index f3a8f13f28..6fe6011a66 100644 --- a/modules/scala-akka-http/src/test/scala/core/issues/Issue61.scala +++ b/modules/scala-akka-http/src/test/scala/core/issues/Issue61.scala @@ -12,7 +12,7 @@ import dev.guardrail.generators.scala.ScalaGeneratorMappings.scalaInterpreter import dev.guardrail.terms.protocol.RandomType class Issue61 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -35,7 +35,7 @@ class Issue61 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(RandomType(_, tpe) :: _ :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") tpe.structure shouldBe t"Vector[String]".structure } @@ -45,7 +45,7 @@ class Issue61 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(_ :: RandomType(_, tpe) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") tpe.structure shouldBe t"Long".structure } diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpClientGeneratorTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpClientGeneratorTest.scala index b6b380da95..ca03786443 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpClientGeneratorTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpClientGeneratorTest.scala @@ -11,7 +11,7 @@ import org.scalatest.matchers.should.Matchers class AkkaHttpClientGeneratorTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = s""" + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io |paths: @@ -116,7 +116,7 @@ class AkkaHttpClientGeneratorTest extends AnyFunSuite with Matchers with Swagger _, Clients(Client(tags, className, _, staticDefns, cls, _) :: Nil, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) tags should equal(Seq("store")) @@ -186,7 +186,7 @@ class AkkaHttpClientGeneratorTest extends AnyFunSuite with Matchers with Swagger _, Clients(List(Client(tags, className, _, staticDefns, cls, _)), Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty.copy(framework = Some("akka-http"), tracing = true), "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(framework = Some("akka-http"), tracing = true), "akka-http") val cmp = companionForStaticDefns(staticDefns) tags should equal(Seq("store")) diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpServerTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpServerTest.scala index 9aa09fbc5b..e93885b9d5 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpServerTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/AkkaHttpServerTest.scala @@ -10,7 +10,7 @@ import org.scalatest.matchers.should.Matchers class AkkaHttpServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = s""" + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io |paths: @@ -130,7 +130,7 @@ class AkkaHttpServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunne _, _, Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val handler = q""" trait StoreHandler { @@ -267,7 +267,7 @@ class AkkaHttpServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunne _, _, Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty.copy(tracing = true), "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(tracing = true), "akka-http") val handler = q""" trait StoreHandler { @@ -404,7 +404,7 @@ class AkkaHttpServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunne _, _, Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty.copy(customExtraction = true), "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(customExtraction = true), "akka-http") val handler = q""" trait StoreHandler[-E] { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/CustomHeaderTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/CustomHeaderTest.scala index 6f6a90cb3b..a5ebad3e85 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/CustomHeaderTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/CustomHeaderTest.scala @@ -10,7 +10,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class CustomHeaderTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -42,7 +42,7 @@ class CustomHeaderTest extends AnyFunSuite with Matchers with SwaggerSpecRunner test("Should produce static parameter constraints") { val (_, Clients(client :: Nil, Nil), Servers(Server(_, _, genHandler, genResource :: Nil) :: Nil, Nil)) = - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val handler = q"""trait Handler { def getFoo(respond: Resource.GetFooResponse.type)(customHeader: Bar): scala.concurrent.Future[Resource.GetFooResponse] }""" diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/DefinitionSpec.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/DefinitionSpec.scala index a8f1dd1eb5..0fbb1b0eb2 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/DefinitionSpec.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/DefinitionSpec.scala @@ -14,7 +14,7 @@ import dev.guardrail.terms.protocol.{ ClassDefinition, EnumDefinition } class DefinitionSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -77,7 +77,7 @@ class DefinitionSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -101,7 +101,7 @@ class DefinitionSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(_ :: _ :: EnumDefinition(_, _, _, _, cls, staticDefns) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -137,7 +137,7 @@ class DefinitionSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(_ :: _ :: _ :: _ :: ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -161,7 +161,7 @@ class DefinitionSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(_ :: _ :: _ :: _ :: _ :: ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/EnumTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/EnumTest.scala index dcc451dc75..67876dbca6 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/EnumTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/EnumTest.scala @@ -15,7 +15,7 @@ import dev.guardrail.terms.protocol.EnumDefinition class EnumTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -64,7 +64,7 @@ class EnumTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(EnumDefinition(_, _, _, _, cls, staticDefns) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -100,7 +100,7 @@ class EnumTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, _, staticDefns, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val client = q""" diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/PropertyExtractors.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/PropertyExtractors.scala index d92c135ad6..041eeb3692 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/PropertyExtractors.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/PropertyExtractors.scala @@ -13,7 +13,7 @@ import dev.guardrail.generators.scala.syntax.companionForStaticDefns import dev.guardrail.terms.protocol.ClassDefinition class PropertyExtractors extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -72,7 +72,7 @@ class PropertyExtractors extends AnyFunSuite with Matchers with SwaggerSpecRunne ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/StaticParametersTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/StaticParametersTest.scala index 4bf5a3afed..cfb5fec2be 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/StaticParametersTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/StaticParametersTest.scala @@ -9,7 +9,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class StaticParametersTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -34,7 +34,7 @@ class StaticParametersTest extends AnyFunSuite with Matchers with SwaggerSpecRun test("Should produce static parameter constraints") { val (_, _, Servers(Server(_, _, genHandler, genResource :: Nil) :: Nil, Nil)) = - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val handler = q""" trait Handler { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/AkkaHttpClientTracingTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/AkkaHttpClientTracingTest.scala index ba31572f54..8531570a7b 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/AkkaHttpClientTracingTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/AkkaHttpClientTracingTest.scala @@ -11,7 +11,7 @@ import org.scalatest.matchers.should.Matchers class AkkaHttpClientTracingTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { test("Manage child tracing span") { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -35,7 +35,7 @@ class AkkaHttpClientTracingTest extends AnyFunSuite with Matchers with SwaggerSp |""".stripMargin val (_, Clients(Client(_, _, _, _, cls, _) :: _, Nil), _) = - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty.copy(tracing = true), "akka-http") + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(tracing = true), "akka-http") val client = q""" class BarBazClient(host: String = "http://localhost:1234", clientName: String = "foo-bar-baz")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { @@ -68,7 +68,7 @@ class AkkaHttpClientTracingTest extends AnyFunSuite with Matchers with SwaggerSp } test("Manage child span with tags") { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -91,7 +91,7 @@ class AkkaHttpClientTracingTest extends AnyFunSuite with Matchers with SwaggerSp _, Clients(Client(tags, className, _, _, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty.copy(tracing = true), "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(tracing = true), "akka-http") val client = q""" class BarBazClient(host: String = "http://localhost:1234", clientName: String = "foo-bar-baz")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/BasicTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/BasicTest.scala index caa4528a68..a1ccd7aac5 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/BasicTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/BasicTest.scala @@ -14,7 +14,7 @@ import dev.guardrail.generators.{ Client, Clients } import dev.guardrail.terms.protocol.{ ClassDefinition, RandomType } class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -79,7 +79,7 @@ class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(RandomType(_, tpe) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") tpe.structure should equal(t"io.circe.Json".structure) } @@ -89,7 +89,7 @@ class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(_ :: ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -114,7 +114,7 @@ class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, _, _, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val client = q""" class Client(host: String = "http://localhost:1234")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/DefaultParametersTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/DefaultParametersTest.scala index be2aac3890..3d03396a2f 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/DefaultParametersTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/DefaultParametersTest.scala @@ -11,7 +11,7 @@ import org.scalatest.matchers.should.Matchers class DefaultParametersTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger = s""" + val spec = s""" |swagger: '2.0' |host: petstore.swagger.io |paths: @@ -127,7 +127,7 @@ class DefaultParametersTest extends AnyFunSuite with Matchers with SwaggerSpecRu _, Clients(Client(tags, className, _, staticDefns, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) tags should equal(Seq("store")) diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/FormFieldsTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/FormFieldsTest.scala index 30459a1909..d4172b789b 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/FormFieldsTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/FormFieldsTest.scala @@ -9,7 +9,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class FormFieldsTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -47,7 +47,7 @@ class FormFieldsTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, _, _, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val client = q""" class Client(host: String = "http://localhost:1234")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HardcodedQSSpec.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HardcodedQSSpec.scala index 49f20b314c..328a3d698c 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HardcodedQSSpec.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HardcodedQSSpec.scala @@ -9,7 +9,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class HardcodedQSSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -51,7 +51,7 @@ class HardcodedQSSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, _, _, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val client = q""" class Client(host: String = "http://localhost:1234")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HttpBodiesTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HttpBodiesTest.scala index 1ddf69d4f8..e78781614e 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HttpBodiesTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/HttpBodiesTest.scala @@ -9,7 +9,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class HttpBodiesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -89,7 +89,7 @@ class HttpBodiesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, _, _, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val client = q""" class Client(host: String = "http://localhost:1234")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/MultipartTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/MultipartTest.scala index 3574b3c408..12c09c7e50 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/MultipartTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/MultipartTest.scala @@ -9,7 +9,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class MultipartTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -52,7 +52,7 @@ class MultipartTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(_, className, _, _, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val client = q""" class Client(host: String = "http://localhost:1234")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/ParamConflictsTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/ParamConflictsTest.scala index 774a71e788..ff024712aa 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/ParamConflictsTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/ParamConflictsTest.scala @@ -15,7 +15,7 @@ import dev.guardrail.terms.protocol.ClassDefinition class ParamConflictsTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -54,7 +54,7 @@ class ParamConflictsTest extends AnyFunSuite with Matchers with SwaggerSpecRunne _, Clients(Client(tags, className, _, _, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val client = q""" class Client(host: String = "http://localhost:1234")(implicit httpClient: HttpRequest => Future[HttpResponse], ec: ExecutionContext, mat: Materializer) { @@ -90,7 +90,7 @@ class ParamConflictsTest extends AnyFunSuite with Matchers with SwaggerSpecRunne ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/SchemeTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/SchemeTest.scala index a10b455a48..efe65003f8 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/SchemeTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/SchemeTest.scala @@ -11,7 +11,7 @@ import org.scalatest.matchers.should.Matchers class SchemeTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -38,7 +38,7 @@ class SchemeTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { test("Use first scheme") { val (_, Clients(Client(_, clientName, _, staticDefns, cls, _) :: _, Nil), _) = - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val companion = q""" diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/contentType/TextPlainTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/contentType/TextPlainTest.scala index 611442d717..ffb7f0337f 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/contentType/TextPlainTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/client/contentType/TextPlainTest.scala @@ -10,7 +10,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class TextPlainTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -40,7 +40,7 @@ class TextPlainTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, _, staticDefns, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val companion = q""" diff --git a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/server/FormFieldsTest.scala b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/server/FormFieldsTest.scala index 5ad87ab767..97bfc5499c 100644 --- a/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/server/FormFieldsTest.scala +++ b/modules/scala-akka-http/src/test/scala/tests/generators/akkaHttp/server/FormFieldsTest.scala @@ -10,7 +10,7 @@ import org.scalatest.matchers.should.Matchers class FormFieldsServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -49,7 +49,7 @@ class FormFieldsServerTest extends AnyFunSuite with Matchers with SwaggerSpecRun _, _, Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val handler = q""" trait Handler { diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue144.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue144.scala index 8277edfa09..7de3b03bec 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue144.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue144.scala @@ -12,7 +12,7 @@ class Issue144 extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io @@ -34,7 +34,7 @@ class Issue144 extends AnyFunSuite with Matchers with SwaggerSpecRunner { def testVersion(version: Http4sVersion): Unit = test(s"$version - Ensure mapRoute is generated") { - val (_, _, Servers(Server(_, _, _, genResource :: _) :: Nil, _)) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + val (_, _, Servers(Server(_, _, _, genResource :: _) :: Nil, _)) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val resource = q""" diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue165.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue165.scala index 23ad2a87f0..0db0be6d44 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue165.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue165.scala @@ -12,7 +12,7 @@ class Issue165 extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io @@ -42,7 +42,7 @@ class Issue165 extends AnyFunSuite with Matchers with SwaggerSpecRunner { def testVersion(version: Http4sVersion): Unit = test(s"$version - Ensure routes are generated") { - val (_, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, Nil)) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + val (_, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, Nil)) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val handler = q""" trait StoreHandler[F[_]] { diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue166.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue166.scala index d85bf2fc24..da73535d0f 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue166.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue166.scala @@ -19,7 +19,7 @@ import dev.guardrail.terms.protocol.ClassDefinition class Issue166 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -58,7 +58,7 @@ class Issue166 extends AnyFunSuite with Matchers with SwaggerSpecRunner { .prepareDefinitions[ScalaLanguage, Target]( CodegenTarget.Models, Context.empty, - Tracker(new OpenAPIParser().readContents(swagger, new java.util.LinkedList(), opts).getOpenAPI), + Tracker(new OpenAPIParser().readContents(spec, new java.util.LinkedList(), opts).getOpenAPI), List.empty, NonEmptyList.one("support") ) diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue1682.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue1682.scala index 02fa430384..f5ab0d4664 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue1682.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue1682.scala @@ -11,7 +11,7 @@ import dev.guardrail.generators.scala.http4s.Http4sVersion class Issue1682 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io |paths: @@ -35,7 +35,7 @@ class Issue1682 extends AnyFunSuite with Matchers with SwaggerSpecRunner { def testVersion(version: Http4sVersion): Unit = test(s"$version - Test HTTP HEAD support") { - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) } testVersion(Http4sVersion.V0_22) diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue222.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue222.scala index b306ddf4d7..6a8f202a1b 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue222.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue222.scala @@ -16,7 +16,7 @@ class Issue222 extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = + val spec: String = s""" |swagger: '2.0' |info: @@ -83,7 +83,7 @@ class Issue222 extends AnyFunSuite with Matchers with SwaggerSpecRunner { def testVersion(version: Http4sVersion): Unit = { test(s"$version - Ensure case-to-case inheritance is not generated") { val (x @ ProtocolDefinitions(List(request: ClassDefinition[ScalaLanguage], requestFields: ClassDefinition[ScalaLanguage], _, _, _), _, _, _, _), _, _) = - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val List(reqEncoder, reqDecoder) = request.staticDefns.definitions @@ -131,7 +131,7 @@ class Issue222 extends AnyFunSuite with Matchers with SwaggerSpecRunner { test(s"$version - Ensure case-to-case inheritance is not generated, extends two objects") { val (ProtocolDefinitions(List(_, _, request: ClassDefinition[ScalaLanguage], requestFields: ClassDefinition[ScalaLanguage], _), _, _, _, _), _, _) = - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val List(reqEncoder, reqDecoder) = request.staticDefns.definitions @@ -179,7 +179,7 @@ class Issue222 extends AnyFunSuite with Matchers with SwaggerSpecRunner { test(s"$version - Ensure case-to-case inheritance is not generated, extends two objects and two classes") { val (ProtocolDefinitions(List(_, _, _, _, request: ClassDefinition[ScalaLanguage]), _, _, _, _), _, _) = - runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val List(reqEncoder, reqDecoder) = request.staticDefns.definitions diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue223.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue223.scala index d8ad602c88..32a38d1a8e 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue223.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue223.scala @@ -13,7 +13,7 @@ import dev.guardrail.generators.scala.http4s.Http4sVersion import dev.guardrail.terms.protocol.ClassDefinition class Issue223 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -39,7 +39,7 @@ class Issue223 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, c1, _, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) c1.structure shouldBe q"case class Kernel(id: java.util.UUID)".structure } diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue225.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue225.scala index c600ade2b5..cc34ba2591 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue225.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue225.scala @@ -13,7 +13,7 @@ class Issue225 extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io @@ -32,7 +32,7 @@ class Issue225 extends AnyFunSuite with Matchers with SwaggerSpecRunner { def testVersion(version: Http4sVersion): Unit = test(s"$version - Ensure mapRoute is generated") { - val (_, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, Nil)) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + val (_, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, Nil)) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val handler = q""" trait Handler[F[_]] { diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue255.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue255.scala index 86bb3b0ebd..f2816236a3 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue255.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue255.scala @@ -13,7 +13,7 @@ import dev.guardrail.generators.scala.http4s.Http4sVersion import dev.guardrail.terms.protocol.ClassDefinition class Issue255 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -47,7 +47,7 @@ class Issue255 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, c1, _, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val expected = q""" diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue260.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue260.scala index d286e3299f..4ce48a5aea 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue260.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue260.scala @@ -14,7 +14,7 @@ class Issue260 extends AnyFunSpec with Matchers with SwaggerSpecRunner { describe(version.toString()) { describe("LocalDate path param is generated more than once") { - val swagger: String = """ + val spec: String = """ | openapi: "3.0.0" | info: | title: Generator Error Sample @@ -81,7 +81,7 @@ class Issue260 extends AnyFunSpec with Matchers with SwaggerSpecRunner { ) :: Nil, _ // supportDefinitions ) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) it("Ensure LocalDateVar is generated only once") { diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue370.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue370.scala index 9aa1dde480..cdda9ccaf4 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue370.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue370.scala @@ -14,7 +14,7 @@ import dev.guardrail.generators.scala.syntax.companionForStaticDefns import dev.guardrail.terms.protocol.ClassDefinition class Issue370 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -59,7 +59,7 @@ class Issue370 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, c1, s, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val cmp = companionForStaticDefns(s) diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue416.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue416.scala index 31ab2a7e4c..feea6ab06d 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue416.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue416.scala @@ -13,7 +13,7 @@ class Issue416 extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io @@ -42,7 +42,7 @@ class Issue416 extends AnyFunSuite with Matchers with SwaggerSpecRunner { def testVersion(version: Http4sVersion): Unit = test(s"$version - Ensure mapRoute is generated") { - val (_, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, _)) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + val (_, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, _)) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val resource = q""" class Resource[F[_]](mapRoute: (String, Request[F], F[Response[F]]) => F[Response[F]] = (_: String, _: Request[F], r: F[Response[F]]) => r)(implicit F: Async[F]) extends Http4sDsl[F] with CirceInstances { diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue420.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue420.scala index cf82fdfbac..52bd0e5a7c 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue420.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue420.scala @@ -16,7 +16,7 @@ class Issue420 extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = """ + val spec: String = """ |swagger: '2.0' |definitions: | Bar: @@ -38,7 +38,7 @@ class Issue420 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(List(bar: ClassDefinition[ScalaLanguage], foo: ClassDefinition[ScalaLanguage]), _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) cmp(bar.cls, q"case class Bar(id: Option[String] = None)") cmp(foo.cls, q"case class Foo(id: Option[String] = None, otherId: Option[String] = None)") diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue429.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue429.scala index 40ecb6450c..d3bf0c4b07 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue429.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue429.scala @@ -13,7 +13,7 @@ import dev.guardrail.generators.scala.http4s.Http4sVersion import dev.guardrail.terms.protocol.ClassDefinition class Issue429 extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |openapi: 3.0.1 |components: | schemas: @@ -31,7 +31,7 @@ class Issue429 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, _, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val List(_, _, _, statusCodeCompanion) = staticDefns.definitions diff --git a/modules/scala-http4s/src/test/scala/core/issues/Issue538.scala b/modules/scala-http4s/src/test/scala/core/issues/Issue538.scala index b26ba0ba64..cc5c85ffb8 100644 --- a/modules/scala-http4s/src/test/scala/core/issues/Issue538.scala +++ b/modules/scala-http4s/src/test/scala/core/issues/Issue538.scala @@ -18,7 +18,7 @@ class Issue538 extends AnyFunSuite with Matchers with SwaggerSpecRunner { def testVersion(version: Http4sVersion): Unit = { test(s"$version - Test double inheritance - both optional") { - val swagger: String = """ + val spec: String = """ |swagger: '2.0' |definitions: | Bar: @@ -49,14 +49,14 @@ class Issue538 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val companion = companionForStaticDefns(foo.staticDefns) cmp(foo.cls, q"case class Foo(id: Option[String] = None)") } test(s"$version - Test double inheritance - one required") { - val swagger: String = """ + val spec: String = """ |swagger: '2.0' |definitions: | Bar: @@ -88,13 +88,13 @@ class Issue538 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) cmp(foo.cls, q"case class Foo(id: String)") } test(s"$version - Test double inheritance - data redaction") { - val swagger: String = """ + val spec: String = """ |swagger: '2.0' |definitions: | Bar: @@ -127,13 +127,13 @@ class Issue538 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) cmp(foo.cls, q"""case class Foo(id: String) { override def toString: String = "Foo(" + "[redacted]" + ")" }""") } test(s"$version - Test double inheritance - empty to null") { - val swagger: String = """ + val spec: String = """ |swagger: '2.0' |definitions: | Bar: @@ -166,7 +166,7 @@ class Issue538 extends AnyFunSuite with Matchers with SwaggerSpecRunner { ), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val companion = companionForStaticDefns(foo.staticDefns) val expected = diff --git a/modules/scala-http4s/src/test/scala/tests/core/FullyQualifiedNames.scala b/modules/scala-http4s/src/test/scala/tests/core/FullyQualifiedNames.scala index cd2a41d3ea..23c398be93 100644 --- a/modules/scala-http4s/src/test/scala/tests/core/FullyQualifiedNames.scala +++ b/modules/scala-http4s/src/test/scala/tests/core/FullyQualifiedNames.scala @@ -15,7 +15,7 @@ import dev.guardrail.terms.protocol.ClassDefinition class FullyQualifiedNames extends AnyFunSuite with Matchers with SwaggerSpecRunner with ScalaMetaMatchers { - val swagger = + val spec = """ |swagger: "2.0" |definitions: @@ -47,7 +47,7 @@ class FullyQualifiedNames extends AnyFunSuite with Matchers with SwaggerSpecRunn ProtocolDefinitions(List(clz @ ClassDefinition(_, _, fullType, _, _, _)), _, _, _, _), Clients(List(Client(_, _, _, _, client, List(respTrait, respObject))), _), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger, List("_root_", "com", "test"))(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec, List("_root_", "com", "test"))(Context.empty, version.value) clz.fullType shouldEqual t"_root_.com.test.User" client.head.toOption.get shouldEqual q""" diff --git a/modules/scala-http4s/src/test/scala/tests/generators/http4s/BasicTest.scala b/modules/scala-http4s/src/test/scala/tests/generators/http4s/BasicTest.scala index 8cb5d19428..1dbe00a3a7 100644 --- a/modules/scala-http4s/src/test/scala/tests/generators/http4s/BasicTest.scala +++ b/modules/scala-http4s/src/test/scala/tests/generators/http4s/BasicTest.scala @@ -15,7 +15,7 @@ import dev.guardrail.generators.{ Client, Clients } import dev.guardrail.terms.protocol.{ ClassDefinition, RandomType } class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -81,7 +81,7 @@ class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(RandomType(_, tpe) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) tpe.structure should equal(t"io.circe.Json".structure) } @@ -91,7 +91,7 @@ class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(_ :: ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -116,7 +116,7 @@ class BasicTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, _, staticDefns, cls, statements) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val cmp = companionForStaticDefns(staticDefns) val companion = q"""object Client { diff --git a/modules/scala-http4s/src/test/scala/tests/generators/http4s/Http4sServerTest.scala b/modules/scala-http4s/src/test/scala/tests/generators/http4s/Http4sServerTest.scala index 226c8ee55f..228dc4c336 100644 --- a/modules/scala-http4s/src/test/scala/tests/generators/http4s/Http4sServerTest.scala +++ b/modules/scala-http4s/src/test/scala/tests/generators/http4s/Http4sServerTest.scala @@ -12,7 +12,7 @@ class Http4sServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunner import scala.meta._ - val swagger: String = + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io @@ -134,7 +134,7 @@ class Http4sServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunner _, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) val handler = q""" @@ -220,7 +220,7 @@ class Http4sServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunner _, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty.copy(tracing = true), version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(tracing = true), version.value) val handler = q""" @@ -311,7 +311,7 @@ class Http4sServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunner _, _, Servers(Server(_, _, genHandler, genResource :: _) :: Nil, Nil) - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty.copy(customExtraction = true), version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(customExtraction = true), version.value) val handler = q""" trait StoreHandler[F[_], -E] { diff --git a/modules/scala-http4s/src/test/scala/tests/generators/http4s/client/DefaultParametersTest.scala b/modules/scala-http4s/src/test/scala/tests/generators/http4s/client/DefaultParametersTest.scala index 191b855568..5b744b8888 100644 --- a/modules/scala-http4s/src/test/scala/tests/generators/http4s/client/DefaultParametersTest.scala +++ b/modules/scala-http4s/src/test/scala/tests/generators/http4s/client/DefaultParametersTest.scala @@ -12,7 +12,7 @@ import org.scalatest.matchers.should.Matchers class DefaultParametersTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { import scala.meta._ - val swagger: String = s""" + val spec: String = s""" |swagger: '2.0' |host: petstore.swagger.io |paths: @@ -129,7 +129,7 @@ class DefaultParametersTest extends AnyFunSuite with Matchers with SwaggerSpecRu _, Clients(Client(tags, className, _, staticDefns, cls, statements) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, version.value) + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, version.value) tags should equal(Seq("store")) val cmp = companionForStaticDefns(staticDefns) diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala index 9eee4b3ebc..c312ff7651 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala @@ -68,7 +68,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa import Target.targetInstances // TODO: Remove me. This resolves implicit ambiguity from MonadChain override def fromSpec( - swagger: Tracker[OpenAPI], + spec: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], defaultPropertyRequirement: PropertyRequirement @@ -81,7 +81,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa ): Target[ProtocolDefinitions[ScalaLanguage]] = { import Sc._ - val components = swagger.downField("components", _.getComponents()) + val components = spec.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) @@ -939,8 +939,8 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa override def buildAccessor(clsName: String, termName: String) = Target.pure(q"${Term.Name(clsName)}.${Term.Name(termName)}") - private def extractProperties(swagger: Tracker[Schema[_]]) = - swagger + private def extractProperties(spec: Tracker[Schema[_]]) = + spec .refine[Target[List[(String, Tracker[Schema[_]])]]] { case o: ObjectSchema => o }(m => Target.pure(m.downField("properties", _.getProperties()).indexedCosequence.value) ) @@ -1397,7 +1397,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa private def implicitsObject() = Target.pure(None) private def extractSuperClass( - swagger: Tracker[ComposedSchema], + spec: Tracker[ComposedSchema], definitions: List[(String, Tracker[Schema[_]])] ) = { def allParents: Tracker[Schema[_]] => Target[List[(String, Tracker[Schema[_]], List[Tracker[Schema[_]]])]] = @@ -1416,7 +1416,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa case _ => Target.pure(List.empty) } ).getOrElse(Target.pure(List.empty)) - allParents(swagger) + allParents(spec) } private def renderADTStaticDefns( diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala index a0a3eec7cb..ac9b80a0df 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala @@ -138,7 +138,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, import Target.targetInstances // TODO: Remove me. This resolves implicit ambiguity from MonadChain override def fromSpec( - swagger: Tracker[OpenAPI], + spec: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], defaultPropertyRequirement: PropertyRequirement @@ -151,7 +151,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, ): Target[ProtocolDefinitions[ScalaLanguage]] = { import Sc._ - val components = swagger.downField("components", _.getComponents()) + val components = spec.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) @@ -1009,8 +1009,8 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, override def buildAccessor(clsName: String, termName: String) = Target.pure(q"${Term.Name(clsName)}.${Term.Name(termName)}") - private def extractProperties(swagger: Tracker[Schema[_]]) = - swagger + private def extractProperties(spec: Tracker[Schema[_]]) = + spec .refine[Target[List[(String, Tracker[Schema[_]])]]] { case o: ObjectSchema => o }(m => Target.pure(m.downField("properties", _.getProperties()).indexedCosequence.value) ) @@ -1491,7 +1491,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, private def implicitsObject() = Target.pure(None) private def extractSuperClass( - swagger: Tracker[ComposedSchema], + spec: Tracker[ComposedSchema], definitions: List[(String, Tracker[Schema[_]])] ) = { def allParents: Tracker[Schema[_]] => Target[List[(String, Tracker[Schema[_]], List[Tracker[Schema[_]]])]] = @@ -1510,7 +1510,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, case _ => Target.pure(List.empty) } ).getOrElse(Target.pure(List.empty)) - allParents(swagger) + allParents(spec) } private def renderADTStaticDefns( diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala index 2b2ca0f15f..a2dbdc0cae 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala @@ -157,7 +157,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ } override def fromSpec( - swagger: Tracker[OpenAPI], + spec: Tracker[OpenAPI], dtoPackage: List[String], supportPackage: NonEmptyList[String], defaultPropertyRequirement: PropertyRequirement @@ -170,7 +170,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ ): Target[ProtocolDefinitions[ScalaLanguage]] = { import Sc._ - val components = swagger.downField("components", _.getComponents()) + val components = spec.downField("components", _.getComponents()) val definitions = components.flatDownField("schemas", _.getSchemas()).indexedCosequence Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) @@ -1063,8 +1063,8 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ override def buildAccessor(clsName: String, termName: String) = Target.pure(q"${Term.Name(clsName)}.${Term.Name(termName)}") - private def extractProperties(swagger: Tracker[Schema[_]]) = - swagger + private def extractProperties(spec: Tracker[Schema[_]]) = + spec .refine[Target[List[(String, Tracker[Schema[_]])]]] { case o: ObjectSchema => o }(m => Target.pure(m.downField("properties", _.getProperties()).indexedCosequence.value) ) @@ -1738,7 +1738,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ ) private def extractSuperClass( - swagger: Tracker[ComposedSchema], + spec: Tracker[ComposedSchema], definitions: List[(String, Tracker[Schema[_]])] ) = { def allParents: Tracker[Schema[_]] => Target[List[(String, Tracker[Schema[_]], List[Tracker[Schema[_]]])]] = @@ -1757,7 +1757,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ case _ => Target.pure(List.empty) } ).getOrElse(Target.pure(List.empty)) - allParents(swagger) + allParents(spec) } private def renderADTStaticDefns( diff --git a/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala b/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala index f364b454d5..71181ec6fe 100644 --- a/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala +++ b/modules/scala-support/src/test/scala/tests/circe/ArrayValidationTest.scala @@ -21,7 +21,7 @@ import support.SwaggerSpecRunner class ArrayValidationTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner { - val swagger: String = + val spec: String = s""" |swagger: "2.0" |info: @@ -119,7 +119,7 @@ class ArrayValidationTest extends AnyFreeSpec with Matchers with SwaggerSpecRunn val ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _) = circeProtocolGenerator .fromSpec( - Tracker(swaggerFromString(swagger)), + Tracker(swaggerFromString(spec)), dtoPackage = Nil, supportPackage = NonEmptyList.one("foop"), defaultPropertyRequirement = PropertyRequirement.OptionalLegacy diff --git a/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala b/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala index 87da36e86b..4e920ea066 100644 --- a/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala +++ b/modules/scala-support/src/test/scala/tests/circe/BigObjectSpec.scala @@ -24,7 +24,7 @@ import dev.guardrail.terms.protocol.PropertyRequirement class BigObjectSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -149,7 +149,7 @@ class BigObjectSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { implicit val swaggerGenerator = SwaggerGenerator[ScalaLanguage]() val ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _) = circeProtocolGenerator .fromSpec( - Tracker(swaggerFromString(swagger)), + Tracker(swaggerFromString(spec)), dtoPackage = Nil, supportPackage = NonEmptyList.one("foop"), defaultPropertyRequirement = PropertyRequirement.OptionalLegacy diff --git a/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala b/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala index 0a01ebee02..4e6ffc03ba 100644 --- a/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala +++ b/modules/scala-support/src/test/scala/tests/circe/ValidationTest.scala @@ -21,7 +21,7 @@ import support.SwaggerSpecRunner class ValidationTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner { - val swagger: String = + val spec: String = s""" |swagger: "2.0" |info: @@ -69,7 +69,7 @@ class ValidationTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner { implicit val swaggerGenerator = SwaggerGenerator[ScalaLanguage]() val ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _) = circeProtocolGenerator .fromSpec( - Tracker(swaggerFromString(swagger)), + Tracker(swaggerFromString(spec)), dtoPackage = Nil, supportPackage = NonEmptyList.one("foop"), defaultPropertyRequirement = PropertyRequirement.OptionalLegacy diff --git a/src/test/scala/codegen/WritePackageSpec.scala b/src/test/scala/codegen/WritePackageSpec.scala index 431681b483..b4fd89e4bf 100644 --- a/src/test/scala/codegen/WritePackageSpec.scala +++ b/src/test/scala/codegen/WritePackageSpec.scala @@ -17,7 +17,7 @@ import org.scalatest.matchers.should.Matchers import support.SwaggerSpecRunner class WritePackageSpec extends AnyFunSuite with SwaggerSpecRunner with Matchers { - val swagger: OpenAPI = swaggerFromString( + val spec: OpenAPI = swaggerFromString( s""" |swagger: "2.0" |info: @@ -56,7 +56,7 @@ class WritePackageSpec extends AnyFunSuite with SwaggerSpecRunner with Matchers |""".stripMargin ) - def injectSwagger[T](s: OpenAPI, rs: ReadSwagger[T]): T = rs.next(s) + def injectSwagger[T](s: OpenAPI, rs: ReadSpec[T]): T = rs.next(s) def extractPackage(path: Path, results: List[WriteTree]): Term.Ref = { val Some(source"""package ${fooPkg} @@ -83,7 +83,7 @@ class WritePackageSpec extends AnyFunSuite with SwaggerSpecRunner with Matchers .processArgs[ScalaLanguage, Target](args)(scalaInterpreter) ) .toList - .flatMap(x => Target.unsafeExtract(injectSwagger(swagger, x))) + .flatMap(x => Target.unsafeExtract(injectSwagger(spec, x))) val paths = result.map(_.path) @@ -137,7 +137,7 @@ class WritePackageSpec extends AnyFunSuite with SwaggerSpecRunner with Matchers .processArgs[ScalaLanguage, Target](args)(scalaInterpreter) ) .toList - .flatMap(x => Target.unsafeExtract(injectSwagger(swagger, x))) + .flatMap(x => Target.unsafeExtract(injectSwagger(spec, x))) val paths = result.map(_.path) diff --git a/src/test/scala/swagger/VendorExtensionTest.scala b/src/test/scala/swagger/VendorExtensionTest.scala index 42e3703d78..96b2b7f256 100644 --- a/src/test/scala/swagger/VendorExtensionTest.scala +++ b/src/test/scala/swagger/VendorExtensionTest.scala @@ -53,7 +53,7 @@ class VendorExtensionTest extends AnyFunSuite with Matchers { val parseOpts = new ParseOptions parseOpts.setResolve(true) val swagger = new OpenAPIParser().readContents(spec, new util.LinkedList(), parseOpts).getOpenAPI - // VendorExtension(swagger).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Swagger")) + // VendorExtension(spec).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Swagger")) for { (k, v) <- swagger.getPaths.asScala _ = VendorExtension(v).extract[String]("x-scala-garbage") should equal(Some("io.swagger.models.Path")) diff --git a/src/test/scala/tests/core/BacktickTest.scala b/src/test/scala/tests/core/BacktickTest.scala index d37e6a6032..aecadb8d40 100644 --- a/src/test/scala/tests/core/BacktickTest.scala +++ b/src/test/scala/tests/core/BacktickTest.scala @@ -14,7 +14,7 @@ import dev.guardrail.generators.scala.ScalaGeneratorMappings.scalaInterpreter class BacktickTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -74,7 +74,7 @@ class BacktickTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { _, Clients(Client(tags, className, imports, staticDefns, cls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) tags should equal(Seq("dashy-package")) @@ -146,7 +146,7 @@ class BacktickTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -181,7 +181,7 @@ class BacktickTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(_ :: EnumDefinition(_, _, _, _, cls, staticDefns) :: _, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" diff --git a/src/test/scala/tests/core/DereferencingAliasesSpec.scala b/src/test/scala/tests/core/DereferencingAliasesSpec.scala index 12cefab323..e98bc19ba6 100644 --- a/src/test/scala/tests/core/DereferencingAliasesSpec.scala +++ b/src/test/scala/tests/core/DereferencingAliasesSpec.scala @@ -15,7 +15,7 @@ import dev.guardrail.terms.protocol.ClassDefinition class DereferencingAliasesSpec extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger = s""" + val spec = s""" |swagger: "2.0" |info: | title: Whatever @@ -142,7 +142,7 @@ class DereferencingAliasesSpec extends AnyFunSuite with Matchers with SwaggerSpe ProtocolDefinitions(_ :: _ :: _ :: ClassDefinition(_, _, _, cls, staticDefns, _) :: _, _, _, _, _), Clients(Client(_, clientName, _, clientStaticDefns, clientCls, _) :: _, Nil), _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val clientCmp = companionForStaticDefns(clientStaticDefns) diff --git a/src/test/scala/tests/core/ScalaTypesTest.scala b/src/test/scala/tests/core/ScalaTypesTest.scala index 7a3e6c8b47..d7f89a32a7 100644 --- a/src/test/scala/tests/core/ScalaTypesTest.scala +++ b/src/test/scala/tests/core/ScalaTypesTest.scala @@ -14,7 +14,7 @@ import dev.guardrail.terms.protocol.ClassDefinition class ScalaTypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -34,7 +34,7 @@ class ScalaTypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" diff --git a/src/test/scala/tests/core/TrackerTests.scala b/src/test/scala/tests/core/TrackerTests.scala index e6263b9c5f..349a66970a 100644 --- a/src/test/scala/tests/core/TrackerTests.scala +++ b/src/test/scala/tests/core/TrackerTests.scala @@ -131,7 +131,7 @@ Tracker should: "swagger" - { "operationId" in { - val swagger = s""" + val spec = s""" |swagger: "2.0" |host: localhost:1234 |paths: @@ -142,11 +142,11 @@ Tracker should: | description: Success |""".stripMargin val (_, UserError("Missing operationId (.paths./foo.operations.GET.operationId)")) = - runInvalidSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, CodegenTarget.Server, Http4sVersion.V0_23.value) + runInvalidSwaggerSpec(scalaInterpreter)(spec)(Context.empty, CodegenTarget.Server, Http4sVersion.V0_23.value) } "responses" in { - val swagger = s""" + val spec = s""" |swagger: "2.0" |host: localhost:1234 |paths: @@ -155,7 +155,7 @@ Tracker should: | operationId: foo |""".stripMargin val (_, UserError("No responses defined for foo (.paths./foo.operations.GET.responses)")) = - runInvalidSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, CodegenTarget.Server, Http4sVersion.V0_23.value) + runInvalidSwaggerSpec(scalaInterpreter)(spec)(Context.empty, CodegenTarget.Server, Http4sVersion.V0_23.value) } } } diff --git a/src/test/scala/tests/core/TypesTest.scala b/src/test/scala/tests/core/TypesTest.scala index e5802ae2fd..e86ce7f7c8 100644 --- a/src/test/scala/tests/core/TypesTest.scala +++ b/src/test/scala/tests/core/TypesTest.scala @@ -15,7 +15,7 @@ import dev.guardrail.terms.protocol.ClassDefinition class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { test("Generate no definitions") { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -95,7 +95,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q""" @@ -151,7 +151,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { } test("Generates from composed schema") { - val swagger: String = s""" + val spec: String = s""" |swagger: "2.0" |info: | title: Whatever @@ -180,7 +180,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, _, _, _) :: ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q"""case class Types(composed: Option[Types.Composed] = None)""" @@ -206,7 +206,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { } test("Deeply nested structure is generated") { - val swagger = + val spec = s""" |swagger: "2.0" |info: @@ -230,7 +230,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) val definition = q"""case class First(second: Option[First.Second] = None)""" @@ -263,7 +263,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { } test("Inherited nested structure work") { - val swagger = + val spec = s""" |swagger: "2.0" |info: @@ -289,7 +289,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, _, _) :: ClassDefinition(_, _, _, _, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "akka-http") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "akka-http") val cmp = companionForStaticDefns(staticDefns) @@ -316,7 +316,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { } test("Optional fields works") { - val swagger = + val spec = s""" |swagger: "2.0" |info: @@ -348,7 +348,7 @@ class TypesTest extends AnyFunSuite with Matchers with SwaggerSpecRunner { ProtocolDefinitions(ClassDefinition(_, _, _, cls, staticDefns, _) :: Nil, _, _, _, _), _, _ - ) = runSwaggerSpec(scalaInterpreter)(swagger)(Context.empty, "http4s") + ) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty, "http4s") val cmp = companionForStaticDefns(staticDefns) From 9821b30b2262f9966f0a978cbd64d7d740f72819 Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 13:45:34 -0700 Subject: [PATCH 3/8] Break out ModelResolver object --- .../scala/dev/guardrail/SwaggerUtil.scala | 299 +---------------- .../core/extract/VendorExtension.scala | 1 - .../core/resolvers/ModelResolver.scala | 316 ++++++++++++++++++ .../generators/LanguageParameter.scala | 7 +- .../scala/dev/guardrail/terms/Responses.scala | 5 +- .../java/jackson/JacksonGenerator.scala | 17 +- .../scala/circe/CirceProtocolGenerator.scala | 17 +- .../circe/CirceRefinedProtocolGenerator.scala | 17 +- .../jackson/JacksonProtocolGenerator.scala | 19 +- 9 files changed, 364 insertions(+), 334 deletions(-) create mode 100644 modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala diff --git a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala index 86017efe5a..55e5e59f20 100644 --- a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala +++ b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala @@ -7,13 +7,13 @@ import io.swagger.v3.oas.models.security.{ SecurityScheme => SwSecurityScheme } import cats.syntax.all._ import dev.guardrail.core.{ ReifiedRawType, Tracker } import dev.guardrail.core.implicits._ -import dev.guardrail.terms.{ CollectionsLibTerms, LanguageTerms, SchemaLiteral, SchemaProjection, SchemaRef, SecurityScheme, SwaggerTerms } +import dev.guardrail.core.resolvers.ModelResolver +import dev.guardrail.terms.{ CollectionsLibTerms, LanguageTerms, SecurityScheme, SwaggerTerms } import dev.guardrail.terms.framework.FrameworkTerms -import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, Default, Extractable, VendorExtension } +import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, VendorExtension } import dev.guardrail.core.extract.VendorExtension.VendorExtensible._ import dev.guardrail.languages.LA import dev.guardrail.terms.protocol.PropMeta -import scala.jdk.CollectionConverters._ object SwaggerUtil { def customTypeName[L <: LA, F[_], A: VendorExtension.VendorExtensible](v: A)(implicit Cl: CollectionsLibTerms[L, F]): F[Option[String]] = { @@ -37,12 +37,6 @@ object SwaggerUtil { } yield CustomMapTypeName(v, prefixes) } - def modelMetaType[L <: LA, F[_]]( - model: Tracker[Schema[_]], - components: Tracker[Option[Components]] - )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[core.ResolvedType[L]] = - propMetaImpl[L, F](model, components)(Left(_)) - def extractConcreteTypes[L <: LA, F[_]]( definitions: List[(String, Tracker[Schema[_]])], components: Tracker[Option[Components]] @@ -75,7 +69,7 @@ object SwaggerUtil { ) .getOrElse( for { - resolved <- modelMetaType[L, F](schema, components) + resolved <- ModelResolver.modelMetaType[L, F](schema, components) } yield (clsName, resolved) ) } @@ -84,137 +78,6 @@ object SwaggerUtil { PropMeta[L](clsName, tpe) // TODO: We're losing ReifiedRawType here. Perhaps maintain through PropMeta? } } - - // Standard type conversions, as documented in http://swagger.io/specification/#data-types-12 - def determineTypeName[L <: LA, F[_]]( - rawSchema: Tracker[Schema[_]], - customType: Tracker[Option[String]], - components: Tracker[Option[Components]] - )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[(L#Type, ReifiedRawType)] = - Sw.log.function(s"determineTypeName(${rawSchema.unwrapTracker}, ${customType.unwrapTracker})") { - import Sc._ - import Cl._ - import Fw._ - - for { - schemaProjection <- rawSchema - .downField("$ref", _.get$ref()) - .indexedDistribute - .fold[F[Tracker[SchemaProjection]]](rawSchema.map(SchemaLiteral(_): SchemaProjection).pure[F]) { ref => - Sw.dereferenceSchema(ref, components).map(_.map(schema => SchemaRef(SchemaLiteral(schema), ref.unwrapTracker))) - } - customTpe <- customType.indexedDistribute.flatTraverse(x => liftCustomType[L, F](x)) - log = { (fmt: Option[String], t: L#Type) => - fmt.foreach { fmt => - if (customTpe.isEmpty) { - println( - s"Warning: Deprecated behavior: Unsupported format '$fmt' for type '${rawSchema.unwrapTracker - .getType()}', falling back to $t. Please switch definitions to x-scala-type for custom types. (${rawSchema.showHistory})" - ) - } - } - - t: L#Type - } - - (renderType, reifiedRawType) <- { - def extractFormat(func: Option[String] => F[L#Type]): Tracker[Schema[_]] => F[(L#Type, ReifiedRawType)] = { schema => - val rawType = schema.downField("type", _.getType()) - val rawFormat = schema.downField("format", _.getFormat()) - for { - rendered <- func(rawFormat.unwrapTracker) - } yield (rendered, ReifiedRawType.of(rawType.unwrapTracker, rawFormat.unwrapTracker)) - } - def const(value: F[L#Type]): Tracker[Schema[_]] => F[(L#Type, ReifiedRawType)] = extractFormat(_ => value) - - // traverseArraySchema is broken out due to the complexity. - val traverseArraySchema: Tracker[ArraySchema] => F[(L#Type, ReifiedRawType)] = { schema => - schema - .downField("items", _.getItems()) - .cotraverse(itemsSchema => - for { - (found, innerRawType) <- determineTypeName(itemsSchema, Tracker.cloneHistory(schema, None), components) - customArrayType <- SwaggerUtil - .customArrayTypeName(schema) - .flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(schema, x)))) - lifted <- liftVectorType(found, customArrayType) - } yield (lifted, ReifiedRawType.ofVector(innerRawType): ReifiedRawType) - ) - .getOrElse(arrayType(None).map((_, ReifiedRawType.unsafeEmpty))) - } - - schemaProjection - // Dereference SchemaRef - .refine[F[(L#Type, ReifiedRawType)]] { case SchemaRef(_, ref) => ref }(ref => - for { - refName <- fallbackType(ref.unwrapTracker.split("/").lastOption, None) - underlyingSchema <- Sw.dereferenceSchema(ref, components) - } yield ( - refName, - ReifiedRawType.of( - underlyingSchema.downField("type", _.getType()).unwrapTracker, - underlyingSchema.downField("format", _.getFormat()).unwrapTracker - ) - ) - ) - // Explicitly return `string` if ObjectSchema has enum values. Should this go? - .orRefine { case SchemaLiteral(x: ObjectSchema) if Option(x.getEnum).map(_.asScala).exists(_.nonEmpty) => x }( - extractFormat(fmt => stringType(None).map(log(fmt, _))) - ) - // First, match SchemaLiteral's that have conditionals on either the type or format - .orRefine { case SchemaLiteral(x: IntegerSchema) if x.getFormat() == "int32" => x }(const(intType())) - .orRefine { case SchemaLiteral(x: IntegerSchema) if x.getFormat() == "int64" => x }(const(longType())) - .orRefine { case SchemaLiteral(x: NumberSchema) if x.getFormat() == "double" => x }(const(doubleType())) - .orRefine { case SchemaLiteral(x: NumberSchema) if x.getFormat() == "float" => x }(const(floatType())) - .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "binary" => x }(const(fileType(None))) - .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "byte" => x }(const(bytesType())) - .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "email" => x }(const(stringType(None))) - .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "password" => x }(const(stringType(None))) - .orRefine { case SchemaLiteral(x: StringSchema) if x.getType() == "file" => x }(const(fileType(None))) - // Then, fall-back to the base type matchers. - .orRefine { case SchemaLiteral(x: ArraySchema) => x }(traverseArraySchema) - .orRefine { case SchemaLiteral(x: BinarySchema) => x }(const(fileType(None))) - .orRefine { case SchemaLiteral(x: BooleanSchema) => x }(extractFormat(fmt => booleanType(fmt))) - .orRefine { case SchemaLiteral(x: ByteArraySchema) => x }(const(bytesType())) - .orRefine { case SchemaLiteral(x: DateSchema) => x }(const(dateType())) - .orRefine { case SchemaLiteral(x: DateTimeSchema) => x }(const(dateTimeType())) - .orRefine { case SchemaLiteral(x: EmailSchema) => x }(const(stringType(None))) - .orRefine { case SchemaLiteral(x: FileSchema) => x }(const(fileType(None))) - .orRefine { case SchemaLiteral(x: IntegerSchema) => x }(extractFormat(fmt => integerType(fmt))) - .orRefine { case SchemaLiteral(x: JsonSchema) => x }(extractFormat(fmt => objectType(fmt).map(log(fmt, _)))) - .orRefine { case SchemaLiteral(x: MapSchema) => x }(extractFormat(fmt => objectType(fmt).map(log(fmt, _)))) - .orRefine { case SchemaLiteral(x: NumberSchema) => x }(extractFormat(fmt => numberType(fmt).map(log(fmt, _)))) - .orRefine { case SchemaLiteral(x: ObjectSchema) => x }(extractFormat(fmt => objectType(fmt).map(log(fmt, _)))) - .orRefine { case SchemaLiteral(x: PasswordSchema) => x }(const(stringType(None))) - .orRefine { case SchemaLiteral(x: StringSchema) => x }(extractFormat(fmt => stringType(None).map(log(fmt, _)))) - .orRefine { case SchemaLiteral(x: UUIDSchema) => x }(const(uuidType())) - // Finally, attempt to recover if we've gotten all the way down here without knowing what we're dealing with - .orRefineFallback { schemaProjection => - schemaProjection match { - case Tracker(history, SchemaLiteral(x)) => - println( - s"WARNING: Missing type mapping for ${x.getClass} (${history}), please report this at https://github.com/guardrail-dev/guardrail/issues" - ) - case Tracker(history, SchemaRef(schema, ref)) => - println(s"WARNING: Unexpected type mapping missing, $ref (${history})") - } - val schema = schemaProjection.map { - case SchemaLiteral(x) => x - case SchemaRef(SchemaLiteral(x), _) => x - } - val rawType = schema.downField("type", _.getType()) - val rawFormat = schema.downField("format", _.getFormat()) - for { - declType <- fallbackType(rawType.unwrapTracker, rawFormat.unwrapTracker) - } yield (declType, ReifiedRawType.of(rawType.unwrapTracker, rawFormat.unwrapTracker)) - } - } - customTpe <- customType.indexedDistribute.flatTraverse(x => liftCustomType[L, F](x)) - result = customTpe.getOrElse(renderType) - _ <- Sw.log.debug(s"Returning ${result}") - } yield (result, reifiedRawType) - } - def isFile(typeName: String, format: Option[String]): Boolean = (typeName, format) match { case ("string", Some("binary")) => true @@ -223,160 +86,6 @@ object SwaggerUtil { case _ => false } - def propMeta[L <: LA, F[_]](property: Tracker[Schema[_]], components: Tracker[Option[Components]])(implicit - Sc: LanguageTerms[L, F], - Cl: CollectionsLibTerms[L, F], - Sw: SwaggerTerms[L, F], - Fw: FrameworkTerms[L, F] - ): F[core.ResolvedType[L]] = propMetaImpl(property, components)(Left(_)) - - private[this] def liftCustomType[L <: LA, F[_]](s: Tracker[String])(implicit Sc: LanguageTerms[L, F]): F[Option[L#Type]] = { - import Sc._ - val tpe = s.map(_.trim) - if (tpe.unwrapTracker.nonEmpty) { - parseType(tpe) - } else Option.empty[L#Type].pure[F] - } - - def propMetaWithName[L <: LA, F[_]](tpe: L#Type, property: Tracker[Schema[_]], components: Tracker[Option[Components]])(implicit - Sc: LanguageTerms[L, F], - Cl: CollectionsLibTerms[L, F], - Sw: SwaggerTerms[L, F], - Fw: FrameworkTerms[L, F] - ): F[core.ResolvedType[L]] = - propMetaImpl(property, components)( - _.refine[core.ResolvedType[L]] { case schema: ObjectSchema if Option(schema.getProperties).exists(p => !p.isEmpty) => schema }(_ => - core.Resolved[L](tpe, None, None, ReifiedRawType.unsafeEmpty) - ).orRefine { case c: ComposedSchema => c }(_ => core.Resolved[L](tpe, None, None, ReifiedRawType.unsafeEmpty)) - .orRefine { case schema: StringSchema if Option(schema.getEnum).map(_.asScala).exists(_.nonEmpty) => schema }(_ => - core.Resolved[L](tpe, None, None, ReifiedRawType.unsafeEmpty) - ) - .map(_.pure[F]) - ) - - private def resolveScalarTypes[L <: LA, F[_]]( - partial: Either[Tracker[Schema[_]], F[core.ResolvedType[L]]], - components: Tracker[Option[Components]] - )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[core.ResolvedType[L]] = { - import Sw._ - def buildResolveNoDefault[A <: Schema[_]]: Tracker[A] => F[core.ResolvedType[L]] = { a => - for { - customTpeName <- customTypeName(a) - (tpe, rawType) <- determineTypeName[L, F](a, Tracker.cloneHistory(a, customTpeName), components) - } yield core.Resolved[L](tpe, None, None, rawType) - } - - partial - .orRefine { case b: BooleanSchema => b }(buildResolveNoDefault) - .orRefine { case s: StringSchema => s }(buildResolveNoDefault) - .orRefine { case s: EmailSchema => s }(buildResolveNoDefault) - .orRefine { case d: DateSchema => d }(buildResolveNoDefault) - .orRefine { case d: DateTimeSchema => d }(buildResolveNoDefault) - .orRefine { case i: IntegerSchema => i }(buildResolveNoDefault) - .orRefine { case d: NumberSchema => d }(buildResolveNoDefault) - .orRefine { case p: PasswordSchema => p }(buildResolveNoDefault) - .orRefine { case f: FileSchema => f }(buildResolveNoDefault) - .orRefine { case b: BinarySchema => b }(buildResolveNoDefault) - .orRefine { case u: UUIDSchema => u }(buildResolveNoDefault) - .orRefineFallback(x => - fallbackPropertyTypeHandler(x).map(core.Resolved[L](_, None, None, ReifiedRawType.unsafeEmpty)) - ) // This may need to be rawType=string? - } - - private def enrichWithDefault[L <: LA, F[_]](schema: Tracker[Schema[_]])(implicit - Sc: LanguageTerms[L, F], - Cl: CollectionsLibTerms[L, F], - Sw: SwaggerTerms[L, F], - Fw: FrameworkTerms[L, F] - ): core.ResolvedType[L] => F[core.ResolvedType[L]] = { resolved => - import Sc._ - def buildResolve[B: Extractable, A <: Schema[_]: Default.GetDefault](transformLit: B => F[L#Term]): Tracker[A] => F[core.ResolvedType[L]] = { a => - for { - default <- Default(a).extract[B].traverse(transformLit(_)) - } yield resolved match { - case x: core.Resolved[L] => x.copy(defaultValue = default) - case other => other - } - } - schema - .refine[F[core.ResolvedType[L]]] { case b: BooleanSchema => b }(buildResolve(litBoolean)) - .orRefine { case s: StringSchema => s }(buildResolve(litString)) - .orRefine { case s: IntegerSchema => s }(buildResolve(litInt)) - .orRefineFallback(_ => resolved.pure[F]) - } - - private def propMetaImpl[L <: LA, F[_]](property: Tracker[Schema[_]], components: Tracker[Option[Components]])( - strategy: Tracker[Schema[_]] => Either[Tracker[Schema[_]], F[core.ResolvedType[L]]] - )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[core.ResolvedType[L]] = - Sw.log.function("propMeta") { - import Fw._ - import Sc._ - import Cl._ - import Sw._ - - for { - _ <- log.debug(s"property:\n${log.schemaToString(property.unwrapTracker)} (${property.unwrapTracker.getExtensions()}, ${property.showHistory})") - - res <- strategy(property) - .orRefine { case o: ObjectSchema => o }(o => - for { - customTpeName <- customTypeName(o) - customTpe <- customTpeName.flatTraverse(x => liftCustomType[L, F](Tracker.cloneHistory(o, x))) - fallback <- objectType(None) - } yield core.Resolved[L](customTpe.getOrElse(fallback), None, None, ReifiedRawType.unsafeEmpty) - ) - .orRefine { case arr: ArraySchema => arr }(arr => - for { - items <- getItems(arr) - dereferencedItems <- items - .downField("$ref", _.get$ref()) - .indexedDistribute - .fold[F[Tracker[Schema[_]]]](items.pure[F])(ref => dereferenceSchema(ref, components)) - meta <- propMetaImpl[L, F](items, components)(strategy) - itemsRawType = dereferencedItems.downField("type", _.getType()) - itemsRawFormat = dereferencedItems.downField("format", _.getFormat()) - arrayType <- customArrayTypeName(arr).flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(arr, x)))) - res <- meta match { - case core.Resolved(inner, dep, default, _) => - (liftVectorType(inner, arrayType), default.traverse(liftVectorTerm)) - .mapN(core.Resolved[L](_, dep, _, ReifiedRawType.ofVector(ReifiedRawType.of(itemsRawType.unwrapTracker, itemsRawFormat.unwrapTracker)))) - case x: core.Deferred[L] => embedArray(x, arrayType) - case x: core.DeferredArray[L] => embedArray(x, arrayType) - case x: core.DeferredMap[L] => embedArray(x, arrayType) - } - } yield res - ) - .orRefine { case map: MapSchema => map } { map => - val rawType = map.downField("type", _.getType()) - val rawFormat = map.downField("format", _.getFormat()) - for { - rec <- map - .downField("additionalProperties", _.getAdditionalProperties()) - .map(_.getOrElse(false)) - .refine[F[core.ResolvedType[L]]] { case b: java.lang.Boolean => b }(_ => - objectType(None).map(core.Resolved[L](_, None, None, ReifiedRawType.ofMap(ReifiedRawType.unsafeEmpty))) - ) - .orRefine { case s: Schema[_] => s }(s => propMetaImpl[L, F](s, components)(strategy)) - .orRefineFallback { s => - log.debug(s"Unknown structure cannot be reflected: ${s.unwrapTracker} (${s.showHistory})") >> objectType(None) - .map(core.Resolved[L](_, None, None, ReifiedRawType.ofMap(ReifiedRawType.of(rawType.unwrapTracker, rawFormat.unwrapTracker)))) - } - mapType <- customMapTypeName(map).flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(map, x)))) - res <- rec match { - case core.Resolved(inner, dep, _, rawType) => liftMapType(inner, mapType).map(core.Resolved[L](_, dep, None, ReifiedRawType.ofMap(rawType))) - case x: core.DeferredMap[L] => embedMap(x, mapType) - case x: core.DeferredArray[L] => embedMap(x, mapType) - case x: core.Deferred[L] => embedMap(x, mapType) - } - } yield res - } - .orRefine { case ref: Schema[_] if Option(ref.get$ref).isDefined => ref }(ref => getSimpleRef(ref.map(Option.apply _)).map(core.Deferred[L])) - .pure[F] - scalarResolved <- resolveScalarTypes[L, F](res, components) - withDefaults <- enrichWithDefault[L, F](property).apply(scalarResolved) - } yield withDefaults - } - def extractSecuritySchemes[L <: LA, F[_]]( spec: OpenAPI, prefixes: List[String] diff --git a/modules/core/src/main/scala/dev/guardrail/core/extract/VendorExtension.scala b/modules/core/src/main/scala/dev/guardrail/core/extract/VendorExtension.scala index ef3020ac94..1688953e9f 100644 --- a/modules/core/src/main/scala/dev/guardrail/core/extract/VendorExtension.scala +++ b/modules/core/src/main/scala/dev/guardrail/core/extract/VendorExtension.scala @@ -19,7 +19,6 @@ object VendorExtension { } object VendorExtensible { - def build[F](f: F => String => Option[Any]): VendorExtensible[F] = new VendorExtensible[F] { def extract[T](from: F, key: String)(implicit T: Extractable[T]): Option[T] = diff --git a/modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala b/modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala new file mode 100644 index 0000000000..e61f2c0e72 --- /dev/null +++ b/modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala @@ -0,0 +1,316 @@ +package dev.guardrail.core.resolvers + +import dev.guardrail.core +import dev.guardrail.languages.LA +import dev.guardrail.core.{ ReifiedRawType, Tracker } +import dev.guardrail.core.extract.{ Default, Extractable } +import dev.guardrail.terms.{ CollectionsLibTerms, LanguageTerms, SchemaLiteral, SchemaProjection, SchemaRef, SwaggerTerms } +import dev.guardrail.terms.framework.FrameworkTerms +import dev.guardrail.SwaggerUtil + +import cats.syntax.all._ +import io.swagger.v3.oas.models._ +import io.swagger.v3.oas.models.media._ +import scala.jdk.CollectionConverters._ + +object ModelResolver { + def propMeta[L <: LA, F[_]](property: Tracker[Schema[_]], components: Tracker[Option[Components]])(implicit + Sc: LanguageTerms[L, F], + Cl: CollectionsLibTerms[L, F], + Sw: SwaggerTerms[L, F], + Fw: FrameworkTerms[L, F] + ): F[core.ResolvedType[L]] = propMetaImpl(property, components)(Left(_)) + + def propMetaWithName[L <: LA, F[_]](tpe: L#Type, property: Tracker[Schema[_]], components: Tracker[Option[Components]])(implicit + Sc: LanguageTerms[L, F], + Cl: CollectionsLibTerms[L, F], + Sw: SwaggerTerms[L, F], + Fw: FrameworkTerms[L, F] + ): F[core.ResolvedType[L]] = { + implicit val M = Sc.MonadF + + propMetaImpl(property, components)( + _.refine[core.ResolvedType[L]] { case schema: ObjectSchema if Option(schema.getProperties).exists(p => !p.isEmpty) => schema }(_ => + core.Resolved[L](tpe, None, None, ReifiedRawType.unsafeEmpty) + ).orRefine { case c: ComposedSchema => c }(_ => core.Resolved[L](tpe, None, None, ReifiedRawType.unsafeEmpty)) + .orRefine { case schema: StringSchema if Option(schema.getEnum).map(_.asScala).exists(_.nonEmpty) => schema }(_ => + core.Resolved[L](tpe, None, None, ReifiedRawType.unsafeEmpty) + ) + .map(_.pure[F]) + ) + } + + def modelMetaType[L <: LA, F[_]]( + model: Tracker[Schema[_]], + components: Tracker[Option[Components]] + )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[core.ResolvedType[L]] = + propMetaImpl[L, F](model, components)(Left(_)) + + private def propMetaImpl[L <: LA, F[_]](property: Tracker[Schema[_]], components: Tracker[Option[Components]])( + strategy: Tracker[Schema[_]] => Either[Tracker[Schema[_]], F[core.ResolvedType[L]]] + )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[core.ResolvedType[L]] = + Sw.log.function("propMeta") { + import Fw._ + import Sc._ + import Cl._ + import Sw._ + + implicit val M = Sc.MonadF + + for { + _ <- log.debug(s"property:\n${log.schemaToString(property.unwrapTracker)} (${property.unwrapTracker.getExtensions()}, ${property.showHistory})") + + res <- strategy(property) + .orRefine { case o: ObjectSchema => o }(o => + for { + customTpeName <- SwaggerUtil.customTypeName(o) + customTpe <- customTpeName.flatTraverse(x => liftCustomType[L, F](Tracker.cloneHistory(o, x))) + fallback <- objectType(None) + } yield core.Resolved[L](customTpe.getOrElse(fallback), None, None, ReifiedRawType.unsafeEmpty) + ) + .orRefine { case arr: ArraySchema => arr }(arr => + for { + items <- getItems(arr) + dereferencedItems <- items + .downField("$ref", _.get$ref()) + .indexedDistribute + .fold[F[Tracker[Schema[_]]]](items.pure[F])(ref => dereferenceSchema(ref, components)) + meta <- propMetaImpl[L, F](items, components)(strategy) + itemsRawType = dereferencedItems.downField("type", _.getType()) + itemsRawFormat = dereferencedItems.downField("format", _.getFormat()) + arrayType <- SwaggerUtil.customArrayTypeName(arr).flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(arr, x)))) + res <- meta match { + case core.Resolved(inner, dep, default, _) => + (liftVectorType(inner, arrayType), default.traverse(liftVectorTerm)) + .mapN(core.Resolved[L](_, dep, _, ReifiedRawType.ofVector(ReifiedRawType.of(itemsRawType.unwrapTracker, itemsRawFormat.unwrapTracker)))) + case x: core.Deferred[L] => embedArray(x, arrayType) + case x: core.DeferredArray[L] => embedArray(x, arrayType) + case x: core.DeferredMap[L] => embedArray(x, arrayType) + } + } yield res + ) + .orRefine { case map: MapSchema => map } { map => + val rawType = map.downField("type", _.getType()) + val rawFormat = map.downField("format", _.getFormat()) + for { + rec <- map + .downField("additionalProperties", _.getAdditionalProperties()) + .map(_.getOrElse(false)) + .refine[F[core.ResolvedType[L]]] { case b: java.lang.Boolean => b }(_ => + objectType(None).map(core.Resolved[L](_, None, None, ReifiedRawType.ofMap(ReifiedRawType.unsafeEmpty))) + ) + .orRefine { case s: Schema[_] => s }(s => propMetaImpl[L, F](s, components)(strategy)) + .orRefineFallback { s => + log.debug(s"Unknown structure cannot be reflected: ${s.unwrapTracker} (${s.showHistory})") >> objectType(None) + .map(core.Resolved[L](_, None, None, ReifiedRawType.ofMap(ReifiedRawType.of(rawType.unwrapTracker, rawFormat.unwrapTracker)))) + } + mapType <- SwaggerUtil.customMapTypeName(map).flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(map, x)))) + res <- rec match { + case core.Resolved(inner, dep, _, rawType) => liftMapType(inner, mapType).map(core.Resolved[L](_, dep, None, ReifiedRawType.ofMap(rawType))) + case x: core.DeferredMap[L] => embedMap(x, mapType) + case x: core.DeferredArray[L] => embedMap(x, mapType) + case x: core.Deferred[L] => embedMap(x, mapType) + } + } yield res + } + .orRefine { case ref: Schema[_] if Option(ref.get$ref).isDefined => ref }(ref => getSimpleRef(ref.map(Option.apply _)).map(core.Deferred[L])) + .pure[F] + scalarResolved <- resolveScalarTypes[L, F](res, components) + withDefaults <- enrichWithDefault[L, F](property).apply(scalarResolved) + } yield withDefaults + } + + // Standard type conversions, as documented in http://swagger.io/specification/#data-types-12 + def determineTypeName[L <: LA, F[_]]( + rawSchema: Tracker[Schema[_]], + customType: Tracker[Option[String]], + components: Tracker[Option[Components]] + )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[(L#Type, ReifiedRawType)] = + Sw.log.function(s"determineTypeName(${rawSchema.unwrapTracker}, ${customType.unwrapTracker})") { + import Sc._ + import Cl._ + import Fw._ + + implicit val M = Sc.MonadF + + for { + schemaProjection <- rawSchema + .downField("$ref", _.get$ref()) + .indexedDistribute + .fold[F[Tracker[SchemaProjection]]](rawSchema.map(SchemaLiteral(_): SchemaProjection).pure[F]) { ref => + Sw.dereferenceSchema(ref, components).map(_.map(schema => SchemaRef(SchemaLiteral(schema), ref.unwrapTracker))) + } + customTpe <- customType.indexedDistribute.flatTraverse(x => liftCustomType[L, F](x)) + log = { (fmt: Option[String], t: L#Type) => + fmt.foreach { fmt => + if (customTpe.isEmpty) { + println( + s"Warning: Deprecated behavior: Unsupported format '$fmt' for type '${rawSchema.unwrapTracker + .getType()}', falling back to $t. Please switch definitions to x-scala-type for custom types. (${rawSchema.showHistory})" + ) + } + } + + t: L#Type + } + + (renderType, reifiedRawType) <- { + def extractFormat(func: Option[String] => F[L#Type]): Tracker[Schema[_]] => F[(L#Type, ReifiedRawType)] = { schema => + val rawType = schema.downField("type", _.getType()) + val rawFormat = schema.downField("format", _.getFormat()) + for { + rendered <- func(rawFormat.unwrapTracker) + } yield (rendered, ReifiedRawType.of(rawType.unwrapTracker, rawFormat.unwrapTracker)) + } + def const(value: F[L#Type]): Tracker[Schema[_]] => F[(L#Type, ReifiedRawType)] = extractFormat(_ => value) + + // traverseArraySchema is broken out due to the complexity. + val traverseArraySchema: Tracker[ArraySchema] => F[(L#Type, ReifiedRawType)] = { schema => + schema + .downField("items", _.getItems()) + .cotraverse(itemsSchema => + for { + (found, innerRawType) <- determineTypeName(itemsSchema, Tracker.cloneHistory(schema, None), components) + customArrayType <- SwaggerUtil + .customArrayTypeName(schema) + .flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(schema, x)))) + lifted <- liftVectorType(found, customArrayType) + } yield (lifted, ReifiedRawType.ofVector(innerRawType): ReifiedRawType) + ) + .getOrElse(arrayType(None).map((_, ReifiedRawType.unsafeEmpty))) + } + + schemaProjection + // Dereference SchemaRef + .refine[F[(L#Type, ReifiedRawType)]] { case SchemaRef(_, ref) => ref }(ref => + for { + refName <- fallbackType(ref.unwrapTracker.split("/").lastOption, None) + underlyingSchema <- Sw.dereferenceSchema(ref, components) + } yield ( + refName, + ReifiedRawType.of( + underlyingSchema.downField("type", _.getType()).unwrapTracker, + underlyingSchema.downField("format", _.getFormat()).unwrapTracker + ) + ) + ) + // Explicitly return `string` if ObjectSchema has enum values. Should this go? + .orRefine { case SchemaLiteral(x: ObjectSchema) if Option(x.getEnum).map(_.asScala).exists(_.nonEmpty) => x }( + extractFormat(fmt => stringType(None).map(log(fmt, _))) + ) + // First, match SchemaLiteral's that have conditionals on either the type or format + .orRefine { case SchemaLiteral(x: IntegerSchema) if x.getFormat() == "int32" => x }(const(intType())) + .orRefine { case SchemaLiteral(x: IntegerSchema) if x.getFormat() == "int64" => x }(const(longType())) + .orRefine { case SchemaLiteral(x: NumberSchema) if x.getFormat() == "double" => x }(const(doubleType())) + .orRefine { case SchemaLiteral(x: NumberSchema) if x.getFormat() == "float" => x }(const(floatType())) + .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "binary" => x }(const(fileType(None))) + .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "byte" => x }(const(bytesType())) + .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "email" => x }(const(stringType(None))) + .orRefine { case SchemaLiteral(x: StringSchema) if x.getFormat() == "password" => x }(const(stringType(None))) + .orRefine { case SchemaLiteral(x: StringSchema) if x.getType() == "file" => x }(const(fileType(None))) + // Then, fall-back to the base type matchers. + .orRefine { case SchemaLiteral(x: ArraySchema) => x }(traverseArraySchema) + .orRefine { case SchemaLiteral(x: BinarySchema) => x }(const(fileType(None))) + .orRefine { case SchemaLiteral(x: BooleanSchema) => x }(extractFormat(fmt => booleanType(fmt))) + .orRefine { case SchemaLiteral(x: ByteArraySchema) => x }(const(bytesType())) + .orRefine { case SchemaLiteral(x: DateSchema) => x }(const(dateType())) + .orRefine { case SchemaLiteral(x: DateTimeSchema) => x }(const(dateTimeType())) + .orRefine { case SchemaLiteral(x: EmailSchema) => x }(const(stringType(None))) + .orRefine { case SchemaLiteral(x: FileSchema) => x }(const(fileType(None))) + .orRefine { case SchemaLiteral(x: IntegerSchema) => x }(extractFormat(fmt => integerType(fmt))) + .orRefine { case SchemaLiteral(x: JsonSchema) => x }(extractFormat(fmt => objectType(fmt).map(log(fmt, _)))) + .orRefine { case SchemaLiteral(x: MapSchema) => x }(extractFormat(fmt => objectType(fmt).map(log(fmt, _)))) + .orRefine { case SchemaLiteral(x: NumberSchema) => x }(extractFormat(fmt => numberType(fmt).map(log(fmt, _)))) + .orRefine { case SchemaLiteral(x: ObjectSchema) => x }(extractFormat(fmt => objectType(fmt).map(log(fmt, _)))) + .orRefine { case SchemaLiteral(x: PasswordSchema) => x }(const(stringType(None))) + .orRefine { case SchemaLiteral(x: StringSchema) => x }(extractFormat(fmt => stringType(None).map(log(fmt, _)))) + .orRefine { case SchemaLiteral(x: UUIDSchema) => x }(const(uuidType())) + // Finally, attempt to recover if we've gotten all the way down here without knowing what we're dealing with + .orRefineFallback { schemaProjection => + schemaProjection match { + case Tracker(history, SchemaLiteral(x)) => + println( + s"WARNING: Missing type mapping for ${x.getClass} (${history}), please report this at https://github.com/guardrail-dev/guardrail/issues" + ) + case Tracker(history, SchemaRef(schema, ref)) => + println(s"WARNING: Unexpected type mapping missing, $ref (${history})") + } + val schema = schemaProjection.map { + case SchemaLiteral(x) => x + case SchemaRef(SchemaLiteral(x), _) => x + } + val rawType = schema.downField("type", _.getType()) + val rawFormat = schema.downField("format", _.getFormat()) + for { + declType <- fallbackType(rawType.unwrapTracker, rawFormat.unwrapTracker) + } yield (declType, ReifiedRawType.of(rawType.unwrapTracker, rawFormat.unwrapTracker)) + } + } + customTpe <- customType.indexedDistribute.flatTraverse(x => liftCustomType[L, F](x)) + result = customTpe.getOrElse(renderType) + _ <- Sw.log.debug(s"Returning ${result}") + } yield (result, reifiedRawType) + } + + private def enrichWithDefault[L <: LA, F[_]](schema: Tracker[Schema[_]])(implicit + Sc: LanguageTerms[L, F], + Cl: CollectionsLibTerms[L, F], + Sw: SwaggerTerms[L, F], + Fw: FrameworkTerms[L, F] + ): core.ResolvedType[L] => F[core.ResolvedType[L]] = { resolved => + import Sc._ + implicit val M = Sc.MonadF + def buildResolve[B: Extractable, A <: Schema[_]: Default.GetDefault](transformLit: B => F[L#Term]): Tracker[A] => F[core.ResolvedType[L]] = { a => + for { + default <- Default(a).extract[B].traverse(transformLit(_)) + } yield resolved match { + case x: core.Resolved[L] => x.copy(defaultValue = default) + case other => other + } + } + schema + .refine[F[core.ResolvedType[L]]] { case b: BooleanSchema => b }(buildResolve(litBoolean)) + .orRefine { case s: StringSchema => s }(buildResolve(litString)) + .orRefine { case s: IntegerSchema => s }(buildResolve(litInt)) + .orRefineFallback(_ => resolved.pure[F]) + } + + private[this] def liftCustomType[L <: LA, F[_]](s: Tracker[String])(implicit Sc: LanguageTerms[L, F]): F[Option[L#Type]] = { + import Sc._ + implicit val M = Sc.MonadF + val tpe = s.map(_.trim) + if (tpe.unwrapTracker.nonEmpty) { + parseType(tpe) + } else Option.empty[L#Type].pure[F] + } + + private def resolveScalarTypes[L <: LA, F[_]]( + partial: Either[Tracker[Schema[_]], F[core.ResolvedType[L]]], + components: Tracker[Option[Components]] + )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[core.ResolvedType[L]] = { + import Sw._ + implicit val M = Sc.MonadF + def buildResolveNoDefault[A <: Schema[_]]: Tracker[A] => F[core.ResolvedType[L]] = { a => + for { + customTpeName <- SwaggerUtil.customTypeName(a) + (tpe, rawType) <- determineTypeName[L, F](a, Tracker.cloneHistory(a, customTpeName), components) + } yield core.Resolved[L](tpe, None, None, rawType) + } + + partial + .orRefine { case b: BooleanSchema => b }(buildResolveNoDefault) + .orRefine { case s: StringSchema => s }(buildResolveNoDefault) + .orRefine { case s: EmailSchema => s }(buildResolveNoDefault) + .orRefine { case d: DateSchema => d }(buildResolveNoDefault) + .orRefine { case d: DateTimeSchema => d }(buildResolveNoDefault) + .orRefine { case i: IntegerSchema => i }(buildResolveNoDefault) + .orRefine { case d: NumberSchema => d }(buildResolveNoDefault) + .orRefine { case p: PasswordSchema => p }(buildResolveNoDefault) + .orRefine { case f: FileSchema => f }(buildResolveNoDefault) + .orRefine { case b: BinarySchema => b }(buildResolveNoDefault) + .orRefine { case u: UUIDSchema => u }(buildResolveNoDefault) + .orRefineFallback(x => + fallbackPropertyTypeHandler(x).map(core.Resolved[L](_, None, None, ReifiedRawType.unsafeEmpty)) + ) // This may need to be rawType=string? + } +} diff --git a/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala b/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala index a7ddb7daee..5d6a4bd714 100644 --- a/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala +++ b/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala @@ -6,8 +6,9 @@ import io.swagger.v3.oas.models.parameters._ import io.swagger.v3.oas.models.Components import dev.guardrail._ -import dev.guardrail.core.extract.{ Default, FileHashAlgorithm } import dev.guardrail.core.{ ReifiedRawType, ResolvedType, Tracker } +import dev.guardrail.core.extract.{ Default, FileHashAlgorithm } +import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.generators.syntax._ import dev.guardrail.languages.LA import dev.guardrail.shims._ @@ -84,7 +85,7 @@ object LanguageParameter { customParamTypeName <- SwaggerUtil.customTypeName(param) customSchemaTypeName <- SwaggerUtil.customTypeName(schema.unwrapTracker) customTypeName = Tracker.cloneHistory(schema, customSchemaTypeName).fold(Tracker.cloneHistory(param, customParamTypeName))(_.map(Option.apply)) - (declType, rawType) <- SwaggerUtil.determineTypeName[L, F](schema, customTypeName, components) + (declType, rawType) <- ModelResolver.determineTypeName[L, F](schema, customTypeName, components) defaultValue <- getDefault(schema) res = core.Resolved[L](declType, None, defaultValue, rawType) required = param.downField("required", _.getRequired()).unwrapTracker.getOrElse(false) @@ -111,7 +112,7 @@ object LanguageParameter { case SchemaLiteral(schema) => schema case SchemaRef(SchemaLiteral(schema), _) => schema }) - resolved <- SwaggerUtil.modelMetaType[L, F](schema, components) + resolved <- ModelResolver.modelMetaType[L, F](schema, components) required = param.downField("required", _.getRequired()).unwrapTracker.getOrElse(false) } yield (resolved, required) ) diff --git a/modules/core/src/main/scala/dev/guardrail/terms/Responses.scala b/modules/core/src/main/scala/dev/guardrail/terms/Responses.scala index a4d5e97019..cd8a674c1a 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/Responses.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/Responses.scala @@ -3,9 +3,10 @@ package dev.guardrail.terms import cats.syntax.all._ import dev.guardrail.core import dev.guardrail.core.Tracker +import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.languages.LA import dev.guardrail.terms.framework.FrameworkTerms -import dev.guardrail.{ SwaggerUtil, monadForFrameworkTerms } +import dev.guardrail.monadForFrameworkTerms import dev.guardrail.terms.protocol.StrictProtocolElems import io.swagger.v3.oas.models.Operation import io.swagger.v3.oas.models.Components @@ -55,7 +56,7 @@ object Responses { schema <- content.downField("schema", _.getSchema()).indexedDistribute.toList } yield (contentType, schema)).traverse { case (contentType, prop) => for { - meta <- SwaggerUtil.propMeta[L, F](prop, components) + meta <- ModelResolver.propMeta[L, F](prop, components) resolved <- core.ResolvedType.resolve[L, F](meta, protocolElems) core.Resolved(baseType, _, baseDefaultValue, _) = resolved // TODO: ReifiedRawType is just dropped, should it be considered? } yield (contentType, baseType, baseDefaultValue) diff --git a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala index 97c761bc26..d3629f660b 100644 --- a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala +++ b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala @@ -21,6 +21,7 @@ import scala.reflect.runtime.universe.typeTag import dev.guardrail.SwaggerUtil import dev.guardrail.core +import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.core.extract.{ DataRedaction, Default, EmptyValueIsNull } import dev.guardrail.core.implicits._ import dev.guardrail.core.{ @@ -255,7 +256,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T for { enum <- extractEnum(schema.map(wrapEnumSchema)) customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- SwaggerUtil.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) res <- enum.traverse(validProg(_, tpe, fullType)) } yield res @@ -373,7 +374,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) customType <- SwaggerUtil.customTypeName(prop) - resolvedType <- SwaggerUtil + resolvedType <- ModelResolver .propMeta[JavaLanguage, Target]( prop, components @@ -476,7 +477,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T typeName <- formatTypeName(name).map(formattedName => getClsName(name).append(formattedName)) tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) - resolvedType <- SwaggerUtil.propMetaWithName(tpe, schema, components) + resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) customType <- SwaggerUtil.customTypeName(schema) propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) @@ -589,7 +590,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T tpe <- model.fold[Target[Type]](objectType(None)) { m => for { tpeName <- SwaggerUtil.customTypeName[JavaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- SwaggerUtil.determineTypeName[JavaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -618,7 +619,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T Sw: SwaggerTerms[JavaLanguage, Target] ): Target[ProtocolElems[JavaLanguage]] = for { - deferredTpe <- SwaggerUtil.modelMetaType(arr, components) + deferredTpe <- ModelResolver.modelMetaType(arr, components) tpe <- extractArrayType(deferredTpe, concreteTypes) ret <- typeAlias(clsName, tpe) } yield ret @@ -844,7 +845,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -864,7 +865,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -872,7 +873,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T for { formattedClsName <- formatTypeName(clsName) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) res <- typeAlias(formattedClsName, declType) } yield res ) diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala index c312ff7651..f2d9f8aae5 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala @@ -13,6 +13,7 @@ import scala.reflect.runtime.universe.typeTag import dev.guardrail.core import dev.guardrail.core.extract.{ DataRedaction, Default, EmptyValueIsNull } import dev.guardrail.core.implicits._ +import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.core.{ DataRedacted, DataVisible, EmptyIsEmpty, EmptyIsNull, LiteralRawType, Mappish, ReifiedRawType, SupportDefinition, Tracker } import dev.guardrail.generators.ProtocolGenerator.{ WrapEnumSchema, wrapNumberEnumSchema, wrapObjectEnumSchema, wrapStringEnumSchema } import dev.guardrail.generators.protocol.{ ClassChild, ClassHierarchy, ClassParent } @@ -148,7 +149,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -168,7 +169,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -176,7 +177,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa for { formattedClsName <- formatTypeName(clsName) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) res <- typeAlias(formattedClsName, declType) } yield res ) @@ -280,7 +281,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa for { enum <- extractEnum(schema.map(wrapEnumSchema)) customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- SwaggerUtil.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) res <- enum.traverse(validProg(_, tpe, fullType)) } yield res @@ -343,7 +344,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) customType <- SwaggerUtil.customTypeName(prop) - resolvedType <- SwaggerUtil + resolvedType <- ModelResolver .propMeta[ScalaLanguage, Target]( prop, components @@ -587,7 +588,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa typeName <- formatTypeName(name).map(formattedName => getClsName(name).append(formattedName)) tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) - resolvedType <- SwaggerUtil.propMetaWithName(tpe, schema, components) + resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) customType <- SwaggerUtil.customTypeName(schema) propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) @@ -702,7 +703,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa tpe <- model.fold[Target[scala.meta.Type]](objectType(None)) { m => for { tpeName <- SwaggerUtil.customTypeName[ScalaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -731,7 +732,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = for { - deferredTpe <- SwaggerUtil.modelMetaType(arr, components) + deferredTpe <- ModelResolver.modelMetaType(arr, components) tpe <- extractArrayType(deferredTpe, concreteTypes) ret <- typeAlias(clsName, tpe) } yield ret diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala index ac9b80a0df..1003b4c261 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala @@ -14,6 +14,7 @@ import scala.reflect.runtime.universe.typeTag import dev.guardrail.core import dev.guardrail.core.extract.Default import dev.guardrail.core.extract.{ DataRedaction, EmptyValueIsNull } +import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.core.{ DataRedacted, DataVisible, EmptyIsEmpty, EmptyIsNull, LiteralRawType, Mappish, ReifiedRawType, SupportDefinition, Tracker } import dev.guardrail.generators.ProtocolGenerator.{ WrapEnumSchema, wrapNumberEnumSchema, wrapObjectEnumSchema, wrapStringEnumSchema } import dev.guardrail.generators.protocol.{ ClassChild, ClassHierarchy, ClassParent } @@ -218,7 +219,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -238,7 +239,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -246,7 +247,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, for { formattedClsName <- formatTypeName(clsName) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) res <- typeAlias(formattedClsName, declType) } yield res ) @@ -350,7 +351,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, for { enum <- extractEnum(schema.map(wrapEnumSchema)) customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- SwaggerUtil.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) res <- enum.traverse(validProg(_, tpe, fullType)) } yield res @@ -413,7 +414,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) customType <- SwaggerUtil.customTypeName(prop) - resolvedType <- SwaggerUtil + resolvedType <- ModelResolver .propMeta[ScalaLanguage, Target]( prop, components @@ -657,7 +658,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, typeName <- formatTypeName(name).map(formattedName => getClsName(name).append(formattedName)) tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) - resolvedType <- SwaggerUtil.propMetaWithName(tpe, schema, components) + resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) customType <- SwaggerUtil.customTypeName(schema) propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) @@ -772,7 +773,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, tpe <- model.fold[Target[scala.meta.Type]](objectType(None)) { m => for { tpeName <- SwaggerUtil.customTypeName[ScalaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -801,7 +802,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = for { - deferredTpe <- SwaggerUtil.modelMetaType(arr, components) + deferredTpe <- ModelResolver.modelMetaType(arr, components) tpe <- extractArrayType(deferredTpe, concreteTypes) ret <- typeAlias(clsName, tpe) } yield ret diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala index a2dbdc0cae..841019621c 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala @@ -11,8 +11,9 @@ import scala.meta._ import scala.reflect.runtime.universe.typeTag import dev.guardrail.core -import dev.guardrail.core.extract.{ DataRedaction, Default, EmptyValueIsNull } +import dev.guardrail.core.extract.{ CustomMapTypeName, DataRedaction, Default, EmptyValueIsNull } import dev.guardrail.core.{ DataRedacted, DataVisible, EmptyIsEmpty, EmptyIsNull, LiteralRawType, Mappish, ReifiedRawType, SupportDefinition, Tracker } +import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.generators.ProtocolGenerator.{ WrapEnumSchema, wrapNumberEnumSchema, wrapObjectEnumSchema, wrapStringEnumSchema } import dev.guardrail.generators.protocol.{ ClassChild, ClassHierarchy, ClassParent } import dev.guardrail.generators.scala.{ JacksonModelGenerator, ScalaGenerator, ScalaLanguage } @@ -237,7 +238,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -257,7 +258,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ components ) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) @@ -265,7 +266,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ for { formattedClsName <- formatTypeName(clsName) customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) res <- typeAlias(formattedClsName, declType) } yield res ) @@ -369,7 +370,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ for { enum <- extractEnum(schema.map(wrapEnumSchema)) customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- SwaggerUtil.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) res <- enum.traverse(validProg(_, tpe, fullType)) } yield res @@ -432,7 +433,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) customType <- SwaggerUtil.customTypeName(prop) - resolvedType <- SwaggerUtil + resolvedType <- ModelResolver .propMeta[ScalaLanguage, Target]( prop, components @@ -675,7 +676,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ typeName <- formatTypeName(name).map(formattedName => getClsName(name).append(formattedName)) tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) - resolvedType <- SwaggerUtil.propMetaWithName(tpe, schema, components) + resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) customType <- SwaggerUtil.customTypeName(schema) propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) @@ -790,7 +791,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ tpe <- model.fold[Target[scala.meta.Type]](objectType(None)) { m => for { tpeName <- SwaggerUtil.customTypeName[ScalaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- SwaggerUtil.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -819,7 +820,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = for { - deferredTpe <- SwaggerUtil.modelMetaType(arr, components) + deferredTpe <- ModelResolver.modelMetaType(arr, components) tpe <- extractArrayType(deferredTpe, concreteTypes) ret <- typeAlias(clsName, tpe) } yield ret From 50451c321e0b768c3a3496cdbee9f03343edbd38 Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 13:50:38 -0700 Subject: [PATCH 4/8] Further break out functions from SwaggerUtil --- .../scala/dev/guardrail/SwaggerUtil.scala | 40 ++++--------------- .../generators/SwaggerGenerator.scala | 29 ++++++++++++-- 2 files changed, 34 insertions(+), 35 deletions(-) diff --git a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala index 55e5e59f20..fd204d7ef3 100644 --- a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala +++ b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala @@ -2,7 +2,6 @@ package dev.guardrail import io.swagger.v3.oas.models._ import io.swagger.v3.oas.models.media._ -import io.swagger.v3.oas.models.parameters.RequestBody import io.swagger.v3.oas.models.security.{ SecurityScheme => SwSecurityScheme } import cats.syntax.all._ import dev.guardrail.core.{ ReifiedRawType, Tracker } @@ -37,6 +36,14 @@ object SwaggerUtil { } yield CustomMapTypeName(v, prefixes) } + def isFile(typeName: String, format: Option[String]): Boolean = + (typeName, format) match { + case ("string", Some("binary")) => true + case ("file", _) => true + case ("binary", _) => true + case _ => false + } + def extractConcreteTypes[L <: LA, F[_]]( definitions: List[(String, Tracker[Schema[_]])], components: Tracker[Option[Components]] @@ -78,13 +85,6 @@ object SwaggerUtil { PropMeta[L](clsName, tpe) // TODO: We're losing ReifiedRawType here. Perhaps maintain through PropMeta? } } - def isFile(typeName: String, format: Option[String]): Boolean = - (typeName, format) match { - case ("string", Some("binary")) => true - case ("file", _) => true - case ("binary", _) => true - case _ => false - } def extractSecuritySchemes[L <: LA, F[_]]( spec: OpenAPI, @@ -113,28 +113,4 @@ object SwaggerUtil { } .map(_.toMap) } - - def copyOperation(operation: Operation): Operation = - new Operation() - .tags(operation.getTags) - .summary(operation.getSummary) - .description(operation.getDescription) - .externalDocs(operation.getExternalDocs) - .operationId(operation.getOperationId) - .parameters(operation.getParameters) - .requestBody(operation.getRequestBody) - .responses(operation.getResponses) - .callbacks(operation.getCallbacks) - .deprecated(operation.getDeprecated) - .security(operation.getSecurity) - .servers(operation.getServers) - .extensions(operation.getExtensions) - - def copyRequestBody(requestBody: RequestBody): RequestBody = - new RequestBody() - .description(requestBody.getDescription) - .content(requestBody.getContent) - .required(requestBody.getRequired) - .$ref(requestBody.get$ref()) - .extensions(requestBody.getExtensions) } diff --git a/modules/core/src/main/scala/dev/guardrail/generators/SwaggerGenerator.scala b/modules/core/src/main/scala/dev/guardrail/generators/SwaggerGenerator.scala index d4c01dcddc..8d6254b489 100644 --- a/modules/core/src/main/scala/dev/guardrail/generators/SwaggerGenerator.scala +++ b/modules/core/src/main/scala/dev/guardrail/generators/SwaggerGenerator.scala @@ -37,6 +37,30 @@ class SwaggerGenerator[L <: LA] extends SwaggerTerms[L, Target] { (parts.drop(1).toList, parts.last) } + private def copyOperation(operation: Operation): Operation = + new Operation() + .tags(operation.getTags) + .summary(operation.getSummary) + .description(operation.getDescription) + .externalDocs(operation.getExternalDocs) + .operationId(operation.getOperationId) + .parameters(operation.getParameters) + .requestBody(operation.getRequestBody) + .responses(operation.getResponses) + .callbacks(operation.getCallbacks) + .deprecated(operation.getDeprecated) + .security(operation.getSecurity) + .servers(operation.getServers) + .extensions(operation.getExtensions) + + def copyRequestBody(requestBody: RequestBody): RequestBody = + new RequestBody() + .description(requestBody.getDescription) + .content(requestBody.getContent) + .required(requestBody.getRequired) + .$ref(requestBody.get$ref()) + .extensions(requestBody.getExtensions) + override def extractCommonRequestBodies(components: Tracker[Option[Components]]): Target[Map[String, RequestBody]] = Target.pure(components.flatDownField("requestBodies", _.getRequestBodies).unwrapTracker.value.toMap) @@ -108,9 +132,8 @@ class SwaggerGenerator[L <: LA] extends SwaggerTerms[L, Target] { ) { commonRequestBody => Target.pure( operation.map(op => - SwaggerUtil - .copyOperation(op) - .requestBody(SwaggerUtil.copyRequestBody(commonRequestBody)) + copyOperation(op) + .requestBody(copyRequestBody(commonRequestBody)) ) ) } From b2be86f645e7b9bb5751c3fdd04063cf50869e4e Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 19:03:49 -0700 Subject: [PATCH 5/8] Moving extractConcreteTypes to PropMeta --- .../scala/dev/guardrail/SwaggerUtil.scala | 48 +---------------- .../guardrail/terms/protocol/PropMeta.scala | 53 +++++++++++++++++++ .../java/jackson/JacksonGenerator.scala | 2 +- .../scala/circe/CirceProtocolGenerator.scala | 2 +- .../circe/CirceRefinedProtocolGenerator.scala | 2 +- .../jackson/JacksonProtocolGenerator.scala | 2 +- 6 files changed, 58 insertions(+), 51 deletions(-) diff --git a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala index fd204d7ef3..072ca54cb7 100644 --- a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala +++ b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala @@ -1,18 +1,14 @@ package dev.guardrail import io.swagger.v3.oas.models._ -import io.swagger.v3.oas.models.media._ import io.swagger.v3.oas.models.security.{ SecurityScheme => SwSecurityScheme } import cats.syntax.all._ -import dev.guardrail.core.{ ReifiedRawType, Tracker } +import dev.guardrail.core.Tracker import dev.guardrail.core.implicits._ -import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.terms.{ CollectionsLibTerms, LanguageTerms, SecurityScheme, SwaggerTerms } -import dev.guardrail.terms.framework.FrameworkTerms import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, VendorExtension } import dev.guardrail.core.extract.VendorExtension.VendorExtensible._ import dev.guardrail.languages.LA -import dev.guardrail.terms.protocol.PropMeta object SwaggerUtil { def customTypeName[L <: LA, F[_], A: VendorExtension.VendorExtensible](v: A)(implicit Cl: CollectionsLibTerms[L, F]): F[Option[String]] = { @@ -44,48 +40,6 @@ object SwaggerUtil { case _ => false } - def extractConcreteTypes[L <: LA, F[_]]( - definitions: List[(String, Tracker[Schema[_]])], - components: Tracker[Option[Components]] - )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], F: FrameworkTerms[L, F]): F[List[PropMeta[L]]] = { - import Sc._ - for { - entries <- definitions.traverse[F, (String, core.ResolvedType[L])] { case (clsName, schema) => - schema - .refine { case impl: Schema[_] if Option(impl.getProperties()).isDefined || Option(impl.getEnum()).isDefined => impl }(impl => - for { - formattedClsName <- formatTypeName(clsName) - typeName <- pureTypeName(formattedClsName) - widenedTypeName <- widenTypeName(typeName) - } yield (clsName, core.Resolved[L](widenedTypeName, None, None, ReifiedRawType.unsafeEmpty): core.ResolvedType[L]) - ) - .orRefine { case comp: ComposedSchema => comp }(comp => - for { - formattedClsName <- formatTypeName(clsName) - typeName <- pureTypeName(formattedClsName) - widenedTypeName <- widenTypeName(typeName) - parentSimpleRef = comp - .downField("allOf", _.getAllOf) - .indexedDistribute - .headOption - .flatMap(_.downField("$ref", _.get$ref).indexedDistribute) - .map(_.unwrapTracker.split("/").last) - parentTerm <- parentSimpleRef.traverse(n => pureTermName(n)) - resolvedType = core.Resolved[L](widenedTypeName, parentTerm, None, ReifiedRawType.unsafeEmpty): core.ResolvedType[L] - } yield (clsName, resolvedType) - ) - .getOrElse( - for { - resolved <- ModelResolver.modelMetaType[L, F](schema, components) - } yield (clsName, resolved) - ) - } - result <- core.ResolvedType.resolveReferences[L, F](entries) - } yield result.map { case (clsName, core.Resolved(tpe, _, _, _)) => - PropMeta[L](clsName, tpe) // TODO: We're losing ReifiedRawType here. Perhaps maintain through PropMeta? - } - } - def extractSecuritySchemes[L <: LA, F[_]]( spec: OpenAPI, prefixes: List[String] diff --git a/modules/core/src/main/scala/dev/guardrail/terms/protocol/PropMeta.scala b/modules/core/src/main/scala/dev/guardrail/terms/protocol/PropMeta.scala index fa93865bb4..05cc03176b 100644 --- a/modules/core/src/main/scala/dev/guardrail/terms/protocol/PropMeta.scala +++ b/modules/core/src/main/scala/dev/guardrail/terms/protocol/PropMeta.scala @@ -1,5 +1,58 @@ package dev.guardrail.terms.protocol +import cats.syntax.all._ +import io.swagger.v3.oas.models._ +import io.swagger.v3.oas.models.media._ + import dev.guardrail.languages.LA +import dev.guardrail.core.{ ReifiedRawType, Resolved, ResolvedType, Tracker } +import dev.guardrail.core.resolvers.ModelResolver +import dev.guardrail.terms.{ CollectionsLibTerms, LanguageTerms, SwaggerTerms } +import dev.guardrail.terms.framework.FrameworkTerms case class PropMeta[L <: LA](clsName: String, tpe: L#Type) + +object PropMeta { + def extractConcreteTypes[L <: LA, F[_]]( + definitions: List[(String, Tracker[Schema[_]])], + components: Tracker[Option[Components]] + )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], F: FrameworkTerms[L, F]): F[List[PropMeta[L]]] = { + import Sc._ + implicit val M = Sc.MonadF + for { + entries <- definitions.traverse[F, (String, ResolvedType[L])] { case (clsName, schema) => + schema + .refine { case impl: Schema[_] if Option(impl.getProperties()).isDefined || Option(impl.getEnum()).isDefined => impl }(impl => + for { + formattedClsName <- formatTypeName(clsName) + typeName <- pureTypeName(formattedClsName) + widenedTypeName <- widenTypeName(typeName) + } yield (clsName, Resolved[L](widenedTypeName, None, None, ReifiedRawType.unsafeEmpty): ResolvedType[L]) + ) + .orRefine { case comp: ComposedSchema => comp }(comp => + for { + formattedClsName <- formatTypeName(clsName) + typeName <- pureTypeName(formattedClsName) + widenedTypeName <- widenTypeName(typeName) + parentSimpleRef = comp + .downField("allOf", _.getAllOf) + .indexedDistribute + .headOption + .flatMap(_.downField("$ref", _.get$ref).indexedDistribute) + .map(_.unwrapTracker.split("/").last) + parentTerm <- parentSimpleRef.traverse(n => pureTermName(n)) + resolvedType = Resolved[L](widenedTypeName, parentTerm, None, ReifiedRawType.unsafeEmpty): ResolvedType[L] + } yield (clsName, resolvedType) + ) + .getOrElse( + for { + resolved <- ModelResolver.modelMetaType[L, F](schema, components) + } yield (clsName, resolved) + ) + } + result <- ResolvedType.resolveReferences[L, F](entries) + } yield result.map { case (clsName, Resolved(tpe, _, _, _)) => + PropMeta[L](clsName, tpe) // TODO: We're losing ReifiedRawType here. Perhaps maintain through PropMeta? + } + } +} diff --git a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala index d3629f660b..662bfca291 100644 --- a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala +++ b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala @@ -783,7 +783,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) - concreteTypes <- SwaggerUtil.extractConcreteTypes[JavaLanguage, Target](definitions.value, components) + concreteTypes <- PropMeta.extractConcreteTypes[JavaLanguage, Target](definitions.value, components) polyADTs <- hierarchies.traverse(fromPoly(_, concreteTypes, definitions.value, dtoPackage, supportPackage.toList, defaultPropertyRequirement, components)) elems <- definitionsWithoutPoly.traverse { case (clsName, model) => model diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala index f2d9f8aae5..716ad3ef01 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala @@ -87,7 +87,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) - concreteTypes <- SwaggerUtil.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) + concreteTypes <- PropMeta.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) polyADTs <- hierarchies.traverse(fromPoly(_, concreteTypes, definitions.value, dtoPackage, supportPackage.toList, defaultPropertyRequirement, components)) elems <- definitionsWithoutPoly.traverse { case (clsName, model) => model diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala index 1003b4c261..20e034c32e 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala @@ -157,7 +157,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) - concreteTypes <- SwaggerUtil.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) + concreteTypes <- PropMeta.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) polyADTs <- hierarchies.traverse(fromPoly(_, concreteTypes, definitions.value, dtoPackage, supportPackage.toList, defaultPropertyRequirement, components)) elems <- definitionsWithoutPoly.traverse { case (clsName, model) => model diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala index 841019621c..ff44a93293 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala @@ -176,7 +176,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ Sw.log.function("ProtocolGenerator.fromSpec")(for { (hierarchies, definitionsWithoutPoly) <- groupHierarchies(definitions) - concreteTypes <- SwaggerUtil.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) + concreteTypes <- PropMeta.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) polyADTs <- hierarchies.traverse(fromPoly(_, concreteTypes, definitions.value, dtoPackage, supportPackage.toList, defaultPropertyRequirement, components)) elems <- definitionsWithoutPoly.traverse { case (clsName, model) => model From 9108d600f19988354c2ede4ac94fd16202a5c85f Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 19:04:22 -0700 Subject: [PATCH 6/8] Reducing dependency on SwaggerUtil.custom*TypeName functions --- .../scala/dev/guardrail/SwaggerUtil.scala | 21 -------- .../core/resolvers/ModelResolver.scala | 27 +++++----- .../generators/LanguageParameter.scala | 9 ++-- .../java/jackson/JacksonGenerator.scala | 52 +++++++++--------- .../scala/circe/CirceProtocolGenerator.scala | 52 +++++++++--------- .../circe/CirceRefinedProtocolGenerator.scala | 51 +++++++++--------- .../jackson/JacksonProtocolGenerator.scala | 53 ++++++++++--------- 7 files changed, 130 insertions(+), 135 deletions(-) diff --git a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala index 072ca54cb7..e68d7f150e 100644 --- a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala +++ b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala @@ -11,27 +11,6 @@ import dev.guardrail.core.extract.VendorExtension.VendorExtensible._ import dev.guardrail.languages.LA object SwaggerUtil { - def customTypeName[L <: LA, F[_], A: VendorExtension.VendorExtensible](v: A)(implicit Cl: CollectionsLibTerms[L, F]): F[Option[String]] = { - import Cl._ - for { - prefixes <- vendorPrefixes() - } yield CustomTypeName(v, prefixes) - } - - def customArrayTypeName[L <: LA, F[_], A: VendorExtension.VendorExtensible](v: A)(implicit Cl: CollectionsLibTerms[L, F]): F[Option[String]] = { - import Cl._ - for { - prefixes <- vendorPrefixes() - } yield CustomArrayTypeName(v, prefixes) - } - - def customMapTypeName[L <: LA, F[_], A: VendorExtension.VendorExtensible](v: A)(implicit Cl: CollectionsLibTerms[L, F]): F[Option[String]] = { - import Cl._ - for { - prefixes <- vendorPrefixes() - } yield CustomMapTypeName(v, prefixes) - } - def isFile(typeName: String, format: Option[String]): Boolean = (typeName, format) match { case ("string", Some("binary")) => true diff --git a/modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala b/modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala index e61f2c0e72..cc6ca026ff 100644 --- a/modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala +++ b/modules/core/src/main/scala/dev/guardrail/core/resolvers/ModelResolver.scala @@ -3,10 +3,9 @@ package dev.guardrail.core.resolvers import dev.guardrail.core import dev.guardrail.languages.LA import dev.guardrail.core.{ ReifiedRawType, Tracker } -import dev.guardrail.core.extract.{ Default, Extractable } +import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, Default, Extractable } import dev.guardrail.terms.{ CollectionsLibTerms, LanguageTerms, SchemaLiteral, SchemaProjection, SchemaRef, SwaggerTerms } import dev.guardrail.terms.framework.FrameworkTerms -import dev.guardrail.SwaggerUtil import cats.syntax.all._ import io.swagger.v3.oas.models._ @@ -63,9 +62,9 @@ object ModelResolver { res <- strategy(property) .orRefine { case o: ObjectSchema => o }(o => for { - customTpeName <- SwaggerUtil.customTypeName(o) - customTpe <- customTpeName.flatTraverse(x => liftCustomType[L, F](Tracker.cloneHistory(o, x))) - fallback <- objectType(None) + prefixes <- vendorPrefixes() + customTpe <- CustomTypeName(o, prefixes).flatTraverse(x => liftCustomType[L, F](Tracker.cloneHistory(o, x))) + fallback <- objectType(None) } yield core.Resolved[L](customTpe.getOrElse(fallback), None, None, ReifiedRawType.unsafeEmpty) ) .orRefine { case arr: ArraySchema => arr }(arr => @@ -78,7 +77,8 @@ object ModelResolver { meta <- propMetaImpl[L, F](items, components)(strategy) itemsRawType = dereferencedItems.downField("type", _.getType()) itemsRawFormat = dereferencedItems.downField("format", _.getFormat()) - arrayType <- SwaggerUtil.customArrayTypeName(arr).flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(arr, x)))) + prefixes <- vendorPrefixes() + arrayType <- CustomArrayTypeName(arr, prefixes).flatTraverse(x => parseType(Tracker.cloneHistory(arr, x))) res <- meta match { case core.Resolved(inner, dep, default, _) => (liftVectorType(inner, arrayType), default.traverse(liftVectorTerm)) @@ -104,7 +104,8 @@ object ModelResolver { log.debug(s"Unknown structure cannot be reflected: ${s.unwrapTracker} (${s.showHistory})") >> objectType(None) .map(core.Resolved[L](_, None, None, ReifiedRawType.ofMap(ReifiedRawType.of(rawType.unwrapTracker, rawFormat.unwrapTracker)))) } - mapType <- SwaggerUtil.customMapTypeName(map).flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(map, x)))) + prefixes <- vendorPrefixes() + mapType <- CustomMapTypeName(map, prefixes).flatTraverse(x => parseType(Tracker.cloneHistory(map, x))) res <- rec match { case core.Resolved(inner, dep, _, rawType) => liftMapType(inner, mapType).map(core.Resolved[L](_, dep, None, ReifiedRawType.ofMap(rawType))) case x: core.DeferredMap[L] => embedMap(x, mapType) @@ -171,10 +172,9 @@ object ModelResolver { .cotraverse(itemsSchema => for { (found, innerRawType) <- determineTypeName(itemsSchema, Tracker.cloneHistory(schema, None), components) - customArrayType <- SwaggerUtil - .customArrayTypeName(schema) - .flatMap(_.flatTraverse(x => parseType(Tracker.cloneHistory(schema, x)))) - lifted <- liftVectorType(found, customArrayType) + prefixes <- vendorPrefixes() + customArrayType <- CustomArrayTypeName(schema, prefixes).flatTraverse(x => parseType(Tracker.cloneHistory(schema, x))) + lifted <- liftVectorType(found, customArrayType) } yield (lifted, ReifiedRawType.ofVector(innerRawType): ReifiedRawType) ) .getOrElse(arrayType(None).map((_, ReifiedRawType.unsafeEmpty))) @@ -288,12 +288,13 @@ object ModelResolver { partial: Either[Tracker[Schema[_]], F[core.ResolvedType[L]]], components: Tracker[Option[Components]] )(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: SwaggerTerms[L, F], Fw: FrameworkTerms[L, F]): F[core.ResolvedType[L]] = { + import Cl._ import Sw._ implicit val M = Sc.MonadF def buildResolveNoDefault[A <: Schema[_]]: Tracker[A] => F[core.ResolvedType[L]] = { a => for { - customTpeName <- SwaggerUtil.customTypeName(a) - (tpe, rawType) <- determineTypeName[L, F](a, Tracker.cloneHistory(a, customTpeName), components) + prefixes <- vendorPrefixes() + (tpe, rawType) <- determineTypeName[L, F](a, Tracker.cloneHistory(a, CustomTypeName(a, prefixes)), components) } yield core.Resolved[L](tpe, None, None, rawType) } diff --git a/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala b/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala index 5d6a4bd714..e81e3311b3 100644 --- a/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala +++ b/modules/core/src/main/scala/dev/guardrail/generators/LanguageParameter.scala @@ -7,7 +7,7 @@ import io.swagger.v3.oas.models.Components import dev.guardrail._ import dev.guardrail.core.{ ReifiedRawType, ResolvedType, Tracker } -import dev.guardrail.core.extract.{ Default, FileHashAlgorithm } +import dev.guardrail.core.extract.{ CustomTypeName, Default, FileHashAlgorithm } import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.generators.syntax._ import dev.guardrail.languages.LA @@ -82,9 +82,10 @@ object LanguageParameter { case SchemaLiteral(schema) => schema case SchemaRef(SchemaLiteral(schema), _) => schema }) - customParamTypeName <- SwaggerUtil.customTypeName(param) - customSchemaTypeName <- SwaggerUtil.customTypeName(schema.unwrapTracker) - customTypeName = Tracker.cloneHistory(schema, customSchemaTypeName).fold(Tracker.cloneHistory(param, customParamTypeName))(_.map(Option.apply)) + prefixes <- vendorPrefixes() + customTypeName = Tracker + .cloneHistory(schema, CustomTypeName(schema.unwrapTracker, prefixes)) + .fold(Tracker.cloneHistory(param, CustomTypeName(param, prefixes)))(_.map(Option.apply)) (declType, rawType) <- ModelResolver.determineTypeName[L, F](schema, customTypeName, components) defaultValue <- getDefault(schema) res = core.Resolved[L](declType, None, defaultValue, rawType) diff --git a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala index 662bfca291..eef477ef35 100644 --- a/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala +++ b/modules/java-support/src/main/scala/dev/guardrail/generators/java/jackson/JacksonGenerator.scala @@ -19,10 +19,9 @@ import com.github.javaparser.ast.{ Node, NodeList } import scala.jdk.CollectionConverters._ import scala.reflect.runtime.universe.typeTag -import dev.guardrail.SwaggerUtil import dev.guardrail.core import dev.guardrail.core.resolvers.ModelResolver -import dev.guardrail.core.extract.{ DataRedaction, Default, EmptyValueIsNull } +import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, DataRedaction, Default, EmptyValueIsNull } import dev.guardrail.core.implicits._ import dev.guardrail.core.{ DataRedacted, @@ -201,6 +200,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T Sw: SwaggerTerms[JavaLanguage, Target], wrapEnumSchema: WrapEnumSchema[A] ): Target[Either[String, EnumDefinition[JavaLanguage]]] = { + import Cl._ import Sc._ import Sw._ @@ -254,11 +254,11 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T } yield EnumDefinition[JavaLanguage](clsName, classType, fullType, wrappedValues, defn, staticDefns) for { - enum <- extractEnum(schema.map(wrapEnumSchema)) - customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) - fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) - res <- enum.traverse(validProg(_, tpe, fullType)) + enum <- extractEnum(schema.map(wrapEnumSchema)) + prefixes <- vendorPrefixes() + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, CustomTypeName(schema, prefixes)), components) + fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) + res <- enum.traverse(validProg(_, tpe, fullType)) } yield res } @@ -302,15 +302,15 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T schema .refine { case map: MapSchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => map }(map => for { - customTpe <- SwaggerUtil.customMapTypeName(map) - result <- customTpe.fold(emptyMap().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomMapTypeName(map, prefixes).fold(emptyMap().map(Option(_)))(_ => empty) } yield result ) .orRefine { case arr: ArraySchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => arr }( arr => for { - customTpe <- SwaggerUtil.customArrayTypeName(arr) - result <- customTpe.fold(emptyArray().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomArrayTypeName(arr, prefixes).fold(emptyArray().map(Option(_)))(_ => empty) } yield result ) .orRefine { case p: BooleanSchema => p }(p => Default(p).extract[Boolean].fold(empty)(litBoolean(_).map(Some(_)))) @@ -350,6 +350,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T Cl: CollectionsLibTerms[JavaLanguage, Target], Sw: SwaggerTerms[JavaLanguage, Target] ): Target[ProtocolElems[JavaLanguage]] = { + import Cl._ import Sc._ def child(hierarchy: ClassHierarchy[JavaLanguage]): List[String] = @@ -373,7 +374,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T for { typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) - customType <- SwaggerUtil.customTypeName(prop) + prefixes <- vendorPrefixes() resolvedType <- ModelResolver .propMeta[JavaLanguage, Target]( prop, @@ -387,7 +388,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T prop, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(prop, prefixes).isDefined, defValue ) } yield res @@ -425,6 +426,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T Cl: CollectionsLibTerms[JavaLanguage, Target], Sw: SwaggerTerms[JavaLanguage, Target] ): Target[(List[ProtocolParameter[JavaLanguage]], List[NestedProtocolElems[JavaLanguage]])] = { + import Cl._ import Sc._ def getClsName(name: String): NonEmptyList[String] = propertyToTypeLookup.get(name).map(NonEmptyList.of(_)).getOrElse(clsName) @@ -478,7 +480,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) - customType <- SwaggerUtil.customTypeName(schema) + prefixes <- vendorPrefixes() propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) fieldName <- formatFieldName(name) @@ -488,7 +490,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T schema, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(schema, prefixes).isDefined, defValue ) } yield (Tracker.cloneHistory(schema, parameter), maybeNestedDefinition.flatMap(_.toOption)) @@ -574,6 +576,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T Cl: CollectionsLibTerms[JavaLanguage, Target], Sw: SwaggerTerms[JavaLanguage, Target] ): Target[ProtocolElems[JavaLanguage]] = { + import Cl._ import Fw._ val model: Option[Tracker[ObjectSchema]] = abstractModel .refine[Option[Tracker[ObjectSchema]]] { case m: ObjectSchema => m }(x => Option(x)) @@ -587,10 +590,10 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T ) .orRefineFallback(_ => None) for { + prefixes <- vendorPrefixes() tpe <- model.fold[Target[Type]](objectType(None)) { m => for { - tpeName <- SwaggerUtil.customTypeName[JavaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](m, Tracker.cloneHistory(m, CustomTypeName(m, prefixes)), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -776,6 +779,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T Cl: CollectionsLibTerms[JavaLanguage, Target], Sw: SwaggerTerms[JavaLanguage, Target] ): Target[ProtocolDefinitions[JavaLanguage]] = { + import Cl._ import Sc._ val components = spec.downField("components", _.getComponents()) @@ -785,6 +789,7 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T concreteTypes <- PropMeta.extractConcreteTypes[JavaLanguage, Target](definitions.value, components) polyADTs <- hierarchies.traverse(fromPoly(_, concreteTypes, definitions.value, dtoPackage, supportPackage.toList, defaultPropertyRequirement, components)) + prefixes <- vendorPrefixes() elems <- definitionsWithoutPoly.traverse { case (clsName, model) => model .refine { case c: ComposedSchema => c }(comp => @@ -844,9 +849,8 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .orRefine { case x: IntegerSchema => x }(x => @@ -864,16 +868,14 @@ class JacksonGenerator private (implicit Cl: CollectionsLibTerms[JavaLanguage, T defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .valueOr(x => for { formattedClsName <- formatTypeName(clsName) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[JavaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) res <- typeAlias(formattedClsName, declType) } yield res ) diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala index 716ad3ef01..462e683954 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala @@ -11,7 +11,7 @@ import scala.meta.{ Defn, _ } import scala.reflect.runtime.universe.typeTag import dev.guardrail.core -import dev.guardrail.core.extract.{ DataRedaction, Default, EmptyValueIsNull } +import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, DataRedaction, Default, EmptyValueIsNull } import dev.guardrail.core.implicits._ import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.core.{ DataRedacted, DataVisible, EmptyIsEmpty, EmptyIsNull, LiteralRawType, Mappish, ReifiedRawType, SupportDefinition, Tracker } @@ -80,6 +80,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolDefinitions[ScalaLanguage]] = { + import Cl._ import Sc._ val components = spec.downField("components", _.getComponents()) @@ -89,6 +90,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa concreteTypes <- PropMeta.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) polyADTs <- hierarchies.traverse(fromPoly(_, concreteTypes, definitions.value, dtoPackage, supportPackage.toList, defaultPropertyRequirement, components)) + prefixes <- vendorPrefixes() elems <- definitionsWithoutPoly.traverse { case (clsName, model) => model .refine { case c: ComposedSchema => c }(comp => @@ -148,9 +150,9 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .orRefine { case x: IntegerSchema => x }(x => @@ -168,16 +170,14 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .valueOr(x => for { formattedClsName <- formatTypeName(clsName) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) res <- typeAlias(formattedClsName, declType) } yield res ) @@ -226,6 +226,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa Sw: SwaggerTerms[ScalaLanguage, Target], wrapEnumSchema: WrapEnumSchema[A] ): Target[Either[String, EnumDefinition[ScalaLanguage]]] = { + import Cl._ import Sc._ import Sw._ @@ -279,11 +280,11 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa } yield EnumDefinition[ScalaLanguage](clsName, classType, fullType, wrappedValues, defn, staticDefns) for { - enum <- extractEnum(schema.map(wrapEnumSchema)) - customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) - fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) - res <- enum.traverse(validProg(_, tpe, fullType)) + enum <- extractEnum(schema.map(wrapEnumSchema)) + prefixes <- vendorPrefixes() + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, CustomTypeName(schema, prefixes)), components) + fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) + res <- enum.traverse(validProg(_, tpe, fullType)) } yield res } @@ -320,6 +321,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = { + import Cl._ import Sc._ def child(hierarchy: ClassHierarchy[ScalaLanguage]): List[String] = @@ -339,11 +341,11 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa .getOrElse(List.empty[SuperClass[ScalaLanguage]].pure[Target]) props <- extractProperties(hierarchy.model) requiredFields = hierarchy.required ::: hierarchy.children.flatMap(_.required) + prefixes <- vendorPrefixes() params <- props.traverse { case (name, prop) => for { typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) - customType <- SwaggerUtil.customTypeName(prop) resolvedType <- ModelResolver .propMeta[ScalaLanguage, Target]( prop, @@ -357,7 +359,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa prop, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(prop, prefixes).isDefined, defValue ) } yield res @@ -536,6 +538,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[(List[ProtocolParameter[ScalaLanguage]], List[NestedProtocolElems[ScalaLanguage]])] = { + import Cl._ import Sc._ def getClsName(name: String): NonEmptyList[String] = propertyToTypeLookup.get(name).map(NonEmptyList.of(_)).getOrElse(clsName) @@ -582,6 +585,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa } yield defn for { + prefixes <- vendorPrefixes() paramsAndNestedDefinitions <- props.traverse[Target, (Tracker[ProtocolParameter[ScalaLanguage]], Option[NestedProtocolElems[ScalaLanguage]])] { case (name, schema) => for { @@ -589,7 +593,6 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) - customType <- SwaggerUtil.customTypeName(schema) propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) fieldName <- formatFieldName(name) @@ -599,7 +602,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa schema, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(schema, prefixes).isDefined, defValue ) } yield (Tracker.cloneHistory(schema, parameter), maybeNestedDefinition.flatMap(_.toOption)) @@ -687,6 +690,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = { + import Cl._ import Fw._ val model: Option[Tracker[ObjectSchema]] = abstractModel .refine[Option[Tracker[ObjectSchema]]] { case m: ObjectSchema => m }(x => Option(x)) @@ -702,8 +706,8 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa for { tpe <- model.fold[Target[scala.meta.Type]](objectType(None)) { m => for { - tpeName <- SwaggerUtil.customTypeName[ScalaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + prefixes <- vendorPrefixes() + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, CustomTypeName(m, prefixes)), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -823,15 +827,15 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa schema .refine { case map: MapSchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => map }(map => for { - customTpe <- SwaggerUtil.customMapTypeName(map) - result <- customTpe.fold(emptyMap().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomMapTypeName(map, prefixes).fold(emptyMap().map(Option(_)))(_ => empty) } yield result ) .orRefine { case arr: ArraySchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => arr }( arr => for { - customTpe <- SwaggerUtil.customArrayTypeName(arr) - result <- customTpe.fold(emptyArray().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomArrayTypeName(arr, prefixes).fold(emptyArray().map(Option(_)))(_ => empty) } yield result ) .orRefine { case p: BooleanSchema => p }(p => Default(p).extract[Boolean].fold(empty)(litBoolean(_).map(Some(_)))) diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala index 20e034c32e..06e96a233a 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala @@ -13,7 +13,7 @@ import scala.reflect.runtime.universe.typeTag import dev.guardrail.core import dev.guardrail.core.extract.Default -import dev.guardrail.core.extract.{ DataRedaction, EmptyValueIsNull } +import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, DataRedaction, EmptyValueIsNull } import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.core.{ DataRedacted, DataVisible, EmptyIsEmpty, EmptyIsNull, LiteralRawType, Mappish, ReifiedRawType, SupportDefinition, Tracker } import dev.guardrail.generators.ProtocolGenerator.{ WrapEnumSchema, wrapNumberEnumSchema, wrapObjectEnumSchema, wrapStringEnumSchema } @@ -150,6 +150,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolDefinitions[ScalaLanguage]] = { + import Cl._ import Sc._ val components = spec.downField("components", _.getComponents()) @@ -159,6 +160,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, concreteTypes <- PropMeta.extractConcreteTypes[ScalaLanguage, Target](definitions.value, components) polyADTs <- hierarchies.traverse(fromPoly(_, concreteTypes, definitions.value, dtoPackage, supportPackage.toList, defaultPropertyRequirement, components)) + prefixes <- vendorPrefixes() elems <- definitionsWithoutPoly.traverse { case (clsName, model) => model .refine { case c: ComposedSchema => c }(comp => @@ -218,9 +220,8 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .orRefine { case x: IntegerSchema => x }(x => @@ -238,16 +239,14 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .valueOr(x => for { formattedClsName <- formatTypeName(clsName) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) res <- typeAlias(formattedClsName, declType) } yield res ) @@ -296,6 +295,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, Sw: SwaggerTerms[ScalaLanguage, Target], wrapEnumSchema: WrapEnumSchema[A] ): Target[Either[String, EnumDefinition[ScalaLanguage]]] = { + import Cl._ import Sc._ import Sw._ @@ -349,11 +349,11 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, } yield EnumDefinition[ScalaLanguage](clsName, classType, fullType, wrappedValues, defn, staticDefns) for { - enum <- extractEnum(schema.map(wrapEnumSchema)) - customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) - fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) - res <- enum.traverse(validProg(_, tpe, fullType)) + enum <- extractEnum(schema.map(wrapEnumSchema)) + prefixes <- vendorPrefixes() + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, CustomTypeName(schema, prefixes)), components) + fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) + res <- enum.traverse(validProg(_, tpe, fullType)) } yield res } @@ -390,6 +390,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = { + import Cl._ import Sc._ def child(hierarchy: ClassHierarchy[ScalaLanguage]): List[String] = @@ -409,11 +410,11 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, .getOrElse(List.empty[SuperClass[ScalaLanguage]].pure[Target]) props <- extractProperties(hierarchy.model) requiredFields = hierarchy.required ::: hierarchy.children.flatMap(_.required) + prefixes <- vendorPrefixes() params <- props.traverse { case (name, prop) => for { typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) - customType <- SwaggerUtil.customTypeName(prop) resolvedType <- ModelResolver .propMeta[ScalaLanguage, Target]( prop, @@ -427,7 +428,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, prop, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(prop, prefixes).isDefined, defValue ) } yield res @@ -606,6 +607,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[(List[ProtocolParameter[ScalaLanguage]], List[NestedProtocolElems[ScalaLanguage]])] = { + import Cl._ import Sc._ def getClsName(name: String): NonEmptyList[String] = propertyToTypeLookup.get(name).map(NonEmptyList.of(_)).getOrElse(clsName) @@ -652,6 +654,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, } yield defn for { + prefixes <- vendorPrefixes() paramsAndNestedDefinitions <- props.traverse[Target, (Tracker[ProtocolParameter[ScalaLanguage]], Option[NestedProtocolElems[ScalaLanguage]])] { case (name, schema) => for { @@ -659,7 +662,6 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) - customType <- SwaggerUtil.customTypeName(schema) propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) fieldName <- formatFieldName(name) @@ -669,7 +671,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, schema, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(schema, prefixes).isDefined, defValue ) } yield (Tracker.cloneHistory(schema, parameter), maybeNestedDefinition.flatMap(_.toOption)) @@ -757,6 +759,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = { + import Cl._ import Fw._ val model: Option[Tracker[ObjectSchema]] = abstractModel .refine[Option[Tracker[ObjectSchema]]] { case m: ObjectSchema => m }(x => Option(x)) @@ -770,10 +773,10 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, ) .orRefineFallback(_ => None) for { + prefixes <- vendorPrefixes() tpe <- model.fold[Target[scala.meta.Type]](objectType(None)) { m => for { - tpeName <- SwaggerUtil.customTypeName[ScalaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, CustomTypeName(m, prefixes)), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -893,15 +896,15 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, schema .refine { case map: MapSchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => map }(map => for { - customTpe <- SwaggerUtil.customMapTypeName(map) - result <- customTpe.fold(emptyMap().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomMapTypeName(map, prefixes).fold(emptyMap().map(Option(_)))(_ => empty) } yield result ) .orRefine { case arr: ArraySchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => arr }( arr => for { - customTpe <- SwaggerUtil.customArrayTypeName(arr) - result <- customTpe.fold(emptyArray().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomArrayTypeName(arr, prefixes).fold(emptyArray().map(Option(_)))(_ => empty) } yield result ) .orRefine { case p: BooleanSchema => p }(p => Default(p).extract[Boolean].fold(empty)(litBoolean(_).map(Some(_)))) diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala index ff44a93293..85d623b9b3 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala @@ -11,7 +11,7 @@ import scala.meta._ import scala.reflect.runtime.universe.typeTag import dev.guardrail.core -import dev.guardrail.core.extract.{ CustomMapTypeName, DataRedaction, Default, EmptyValueIsNull } +import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, DataRedaction, Default, EmptyValueIsNull } import dev.guardrail.core.{ DataRedacted, DataVisible, EmptyIsEmpty, EmptyIsNull, LiteralRawType, Mappish, ReifiedRawType, SupportDefinition, Tracker } import dev.guardrail.core.resolvers.ModelResolver import dev.guardrail.generators.ProtocolGenerator.{ WrapEnumSchema, wrapNumberEnumSchema, wrapObjectEnumSchema, wrapStringEnumSchema } @@ -169,6 +169,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolDefinitions[ScalaLanguage]] = { + import Cl._ import Sc._ val components = spec.downField("components", _.getComponents()) @@ -237,9 +238,9 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + prefixes <- vendorPrefixes() + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .orRefine { case x: IntegerSchema => x }(x => @@ -257,16 +258,16 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ defaultPropertyRequirement, components ) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) - alias <- typeAlias(formattedClsName, declType) + prefixes <- vendorPrefixes() + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) + alias <- typeAlias(formattedClsName, declType) } yield enum.orElse(model).getOrElse(alias) ) .valueOr(x => for { formattedClsName <- formatTypeName(clsName) - customTypeName <- SwaggerUtil.customTypeName(x) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, customTypeName), components) + prefixes <- vendorPrefixes() + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](x, Tracker.cloneHistory(x, CustomTypeName(x, prefixes)), components) res <- typeAlias(formattedClsName, declType) } yield res ) @@ -315,6 +316,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ Sw: SwaggerTerms[ScalaLanguage, Target], wrapEnumSchema: WrapEnumSchema[A] ): Target[Either[String, EnumDefinition[ScalaLanguage]]] = { + import Cl._ import Sc._ import Sw._ @@ -368,11 +370,11 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ } yield EnumDefinition[ScalaLanguage](clsName, classType, fullType, wrappedValues, defn, staticDefns) for { - enum <- extractEnum(schema.map(wrapEnumSchema)) - customTpeName <- SwaggerUtil.customTypeName(schema) - (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, customTpeName), components) - fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) - res <- enum.traverse(validProg(_, tpe, fullType)) + enum <- extractEnum(schema.map(wrapEnumSchema)) + prefixes <- vendorPrefixes() + (tpe, _) <- ModelResolver.determineTypeName(schema, Tracker.cloneHistory(schema, CustomTypeName(schema, prefixes)), components) + fullType <- selectType(NonEmptyList.ofInitLast(dtoPackage, clsName)) + res <- enum.traverse(validProg(_, tpe, fullType)) } yield res } @@ -409,6 +411,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = { + import Cl._ import Sc._ def child(hierarchy: ClassHierarchy[ScalaLanguage]): List[String] = @@ -432,7 +435,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ for { typeName <- formatTypeName(name).map(formattedName => NonEmptyList.of(hierarchy.name, formattedName)) propertyRequirement = getPropertyRequirement(prop, requiredFields.contains(name), defaultPropertyRequirement) - customType <- SwaggerUtil.customTypeName(prop) + prefixes <- vendorPrefixes() resolvedType <- ModelResolver .propMeta[ScalaLanguage, Target]( prop, @@ -446,7 +449,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ prop, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(prop, prefixes).isDefined, defValue ) } yield res @@ -624,6 +627,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[(List[ProtocolParameter[ScalaLanguage]], List[NestedProtocolElems[ScalaLanguage]])] = { + import Cl._ import Sc._ def getClsName(name: String): NonEmptyList[String] = propertyToTypeLookup.get(name).map(NonEmptyList.of(_)).getOrElse(clsName) @@ -677,7 +681,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ tpe <- selectType(typeName) maybeNestedDefinition <- processProperty(name, schema) resolvedType <- ModelResolver.propMetaWithName(tpe, schema, components) - customType <- SwaggerUtil.customTypeName(schema) + prefixes <- vendorPrefixes() propertyRequirement = getPropertyRequirement(schema, requiredFields.contains(name), defaultPropertyRequirement) defValue <- defaultValue(typeName, schema, propertyRequirement, definitions) fieldName <- formatFieldName(name) @@ -687,7 +691,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ schema, resolvedType, propertyRequirement, - customType.isDefined, + CustomTypeName(schema, prefixes).isDefined, defValue ) } yield (Tracker.cloneHistory(schema, parameter), maybeNestedDefinition.flatMap(_.toOption)) @@ -775,6 +779,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ Cl: CollectionsLibTerms[ScalaLanguage, Target], Sw: SwaggerTerms[ScalaLanguage, Target] ): Target[ProtocolElems[ScalaLanguage]] = { + import Cl._ import Fw._ val model: Option[Tracker[ObjectSchema]] = abstractModel .refine[Option[Tracker[ObjectSchema]]] { case m: ObjectSchema => m }(x => Option(x)) @@ -788,10 +793,10 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ ) .orRefineFallback(_ => None) for { + prefixes <- vendorPrefixes() tpe <- model.fold[Target[scala.meta.Type]](objectType(None)) { m => for { - tpeName <- SwaggerUtil.customTypeName[ScalaLanguage, Target, Tracker[ObjectSchema]](m) - (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, tpeName), components) + (declType, _) <- ModelResolver.determineTypeName[ScalaLanguage, Target](m, Tracker.cloneHistory(m, CustomTypeName(m, prefixes)), components) } yield declType } res <- typeAlias(clsName, tpe) @@ -911,15 +916,15 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ schema .refine { case map: MapSchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => map }(map => for { - customTpe <- SwaggerUtil.customMapTypeName(map) - result <- customTpe.fold(emptyMap().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomMapTypeName(map, prefixes).fold(emptyMap().map(Option(_)))(_ => empty) } yield result ) .orRefine { case arr: ArraySchema if requirement == PropertyRequirement.Required || requirement == PropertyRequirement.RequiredNullable => arr }( arr => for { - customTpe <- SwaggerUtil.customArrayTypeName(arr) - result <- customTpe.fold(emptyArray().map(Option(_)))(_ => empty) + prefixes <- vendorPrefixes() + result <- CustomArrayTypeName(arr, prefixes).fold(emptyArray().map(Option(_)))(_ => empty) } yield result ) .orRefine { case p: BooleanSchema => p }(p => Default(p).extract[Boolean].fold(empty)(litBoolean(_).map(Some(_)))) From 0eef007e577ffdbeea216e4b65b47d576a9578d1 Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 19:31:49 -0700 Subject: [PATCH 7/8] Move isFile out into ProtocolGenerators --- .../src/main/scala/dev/guardrail/SwaggerUtil.scala | 12 ++---------- .../scala/circe/CirceProtocolGenerator.scala | 13 ++++++++++--- .../scala/circe/CirceRefinedProtocolGenerator.scala | 13 ++++++++++--- .../scala/jackson/JacksonProtocolGenerator.scala | 13 ++++++++++--- 4 files changed, 32 insertions(+), 19 deletions(-) diff --git a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala index e68d7f150e..81bf1b9c02 100644 --- a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala +++ b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala @@ -5,20 +5,12 @@ import io.swagger.v3.oas.models.security.{ SecurityScheme => SwSecurityScheme } import cats.syntax.all._ import dev.guardrail.core.Tracker import dev.guardrail.core.implicits._ -import dev.guardrail.terms.{ CollectionsLibTerms, LanguageTerms, SecurityScheme, SwaggerTerms } -import dev.guardrail.core.extract.{ CustomArrayTypeName, CustomMapTypeName, CustomTypeName, VendorExtension } +import dev.guardrail.terms.{ LanguageTerms, SecurityScheme, SwaggerTerms } +import dev.guardrail.core.extract.CustomTypeName import dev.guardrail.core.extract.VendorExtension.VendorExtensible._ import dev.guardrail.languages.LA object SwaggerUtil { - def isFile(typeName: String, format: Option[String]): Boolean = - (typeName, format) match { - case ("string", Some("binary")) => true - case ("file", _) => true - case ("binary", _) => true - case _ => false - } - def extractSecuritySchemes[L <: LA, F[_]]( spec: OpenAPI, prefixes: List[String] diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala index 462e683954..d2a43d6b67 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceProtocolGenerator.scala @@ -38,7 +38,7 @@ import dev.guardrail.terms.{ StringHeldEnum, SwaggerTerms } -import dev.guardrail.{ SwaggerUtil, Target, UserError } +import dev.guardrail.{ Target, UserError } class CirceProtocolGeneratorLoader extends ProtocolGeneratorLoader { type L = ScalaLanguage @@ -192,6 +192,14 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa } yield ProtocolDefinitions[ScalaLanguage](strictElems ++ polyADTElems, protoImports, pkgImports, pkgObjectContents, implicitsObject)) } + private[this] def isFile(typeName: String, format: Option[String]): Boolean = + (typeName, format) match { + case ("string", Some("binary")) => true + case ("file", _) => true + case ("binary", _) => true + case _ => false + } + private[this] def getRequiredFieldsRec(root: Tracker[Schema[_]]): List[String] = { @scala.annotation.tailrec def work(values: List[Tracker[Schema[_]]], acc: List[String]): List[String] = { @@ -993,8 +1001,7 @@ class CirceProtocolGenerator private (circeVersion: CirceModelGenerator, applyVa dataRedaction = DataRedaction(property).getOrElse(DataVisible) (tpe, classDep, rawType) <- meta match { - case core.Resolved(declType, classDep, _, rawType @ LiteralRawType(Some(rawTypeStr), rawFormat)) - if SwaggerUtil.isFile(rawTypeStr, rawFormat) && !isCustomType => + case core.Resolved(declType, classDep, _, rawType @ LiteralRawType(Some(rawTypeStr), rawFormat)) if isFile(rawTypeStr, rawFormat) && !isCustomType => // assume that binary data are represented as a string. allow users to override. Target.pure((t"String", classDep, rawType)) case core.Resolved(declType, classDep, _, rawType) => diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala index 06e96a233a..7b1c3950f7 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/circe/CirceRefinedProtocolGenerator.scala @@ -38,7 +38,7 @@ import dev.guardrail.terms.{ StringHeldEnum, SwaggerTerms } -import dev.guardrail.{ SwaggerUtil, Target, UserError } +import dev.guardrail.{ Target, UserError } class CirceRefinedProtocolGeneratorLoader extends ProtocolGeneratorLoader { type L = ScalaLanguage @@ -261,6 +261,14 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, } yield ProtocolDefinitions[ScalaLanguage](strictElems ++ polyADTElems, protoImports, pkgImports, pkgObjectContents, implicitsObject)) } + private[this] def isFile(typeName: String, format: Option[String]): Boolean = + (typeName, format) match { + case ("string", Some("binary")) => true + case ("file", _) => true + case ("binary", _) => true + case _ => false + } + private[this] def getRequiredFieldsRec(root: Tracker[Schema[_]]): List[String] = { @scala.annotation.tailrec def work(values: List[Tracker[Schema[_]]], acc: List[String]): List[String] = { @@ -1062,8 +1070,7 @@ class CirceRefinedProtocolGenerator private (circeVersion: CirceModelGenerator, dataRedaction = DataRedaction(property).getOrElse(DataVisible) (tpe, classDep, rawType) <- meta match { - case core.Resolved(declType, classDep, _, rawType @ LiteralRawType(Some(rawTypeStr), rawFormat)) - if SwaggerUtil.isFile(rawTypeStr, rawFormat) && !isCustomType => + case core.Resolved(declType, classDep, _, rawType @ LiteralRawType(Some(rawTypeStr), rawFormat)) if isFile(rawTypeStr, rawFormat) && !isCustomType => // assume that binary data are represented as a string. allow users to override. Target.pure((t"String", classDep, rawType)) case core.Resolved(declType, classDep, _, rawType) => diff --git a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala index 85d623b9b3..34d0b72e7b 100644 --- a/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala +++ b/modules/scala-support/src/main/scala/dev/guardrail/generators/scala/jackson/JacksonProtocolGenerator.scala @@ -37,7 +37,7 @@ import dev.guardrail.terms.{ StringHeldEnum, SwaggerTerms } -import dev.guardrail.{ RuntimeFailure, SwaggerUtil, Target, UserError } +import dev.guardrail.{ RuntimeFailure, Target, UserError } class JacksonProtocolGeneratorLoader extends ProtocolGeneratorLoader { type L = ScalaLanguage @@ -282,6 +282,14 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ } yield ProtocolDefinitions[ScalaLanguage](strictElems ++ polyADTElems, protoImports, pkgImports, pkgObjectContents, implicitsObject)) } + private[this] def isFile(typeName: String, format: Option[String]): Boolean = + (typeName, format) match { + case ("string", Some("binary")) => true + case ("file", _) => true + case ("binary", _) => true + case _ => false + } + private[this] def getRequiredFieldsRec(root: Tracker[Schema[_]]): List[String] = { @scala.annotation.tailrec def work(values: List[Tracker[Schema[_]]], acc: List[String]): List[String] = { @@ -1118,8 +1126,7 @@ class JacksonProtocolGenerator private extends ProtocolTerms[ScalaLanguage, Targ dataRedaction = DataRedaction(property).getOrElse(DataVisible) (tpe, classDep, rawType) <- meta match { // TODO: Target is not used - case core.Resolved(declType, classDep, _, rawType @ LiteralRawType(Some(rawTypeStr), rawFormat)) - if SwaggerUtil.isFile(rawTypeStr, rawFormat) && !isCustomType => + case core.Resolved(declType, classDep, _, rawType @ LiteralRawType(Some(rawTypeStr), rawFormat)) if isFile(rawTypeStr, rawFormat) && !isCustomType => // assume that binary data are represented as a string. allow users to override. Target.pure((t"String", classDep, rawType)) case core.Resolved(declType, classDep, _, rawType) => From 401b43c13de8f68662fd4f1edd20677310caf3fa Mon Sep 17 00:00:00 2001 From: Devon Stewart Date: Mon, 9 Oct 2023 19:32:08 -0700 Subject: [PATCH 8/8] Moving extractSecuritySchemes into Common --- .../src/main/scala/dev/guardrail/Common.scala | 34 ++++++++++++++- .../scala/dev/guardrail/SwaggerUtil.scala | 41 ------------------- 2 files changed, 32 insertions(+), 43 deletions(-) delete mode 100644 modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala diff --git a/modules/core/src/main/scala/dev/guardrail/Common.scala b/modules/core/src/main/scala/dev/guardrail/Common.scala index f02ac81cb9..fba962e7e3 100644 --- a/modules/core/src/main/scala/dev/guardrail/Common.scala +++ b/modules/core/src/main/scala/dev/guardrail/Common.scala @@ -1,6 +1,7 @@ package dev.guardrail import _root_.io.swagger.v3.oas.models.OpenAPI +import io.swagger.v3.oas.models.security.{ SecurityScheme => SwSecurityScheme } import cats.data.NonEmptyList import cats.syntax.all._ import cats.Id @@ -8,6 +9,7 @@ import java.nio.file.Path import java.net.URI import dev.guardrail.core.{ SupportDefinition, Tracker } +import dev.guardrail.core.extract.CustomTypeName import dev.guardrail.generators.{ Clients, Servers } import dev.guardrail.generators.ProtocolDefinitions import dev.guardrail.languages.LA @@ -15,12 +17,40 @@ import dev.guardrail.terms.client.ClientTerms import dev.guardrail.terms.framework.FrameworkTerms import dev.guardrail.terms.protocol.RandomType import dev.guardrail.terms.server.ServerTerms -import dev.guardrail.terms.{ CollectionsLibTerms, CoreTerms, LanguageTerms, ProtocolTerms, SecurityRequirements, SwaggerTerms } +import dev.guardrail.terms.{ CollectionsLibTerms, CoreTerms, LanguageTerms, ProtocolTerms, SecurityRequirements, SecurityScheme, SwaggerTerms } object Common { val resolveFile: Path => List[String] => Path = root => _.foldLeft(root)(_.resolve(_)) val resolveFileNel: Path => NonEmptyList[String] => Path = root => _.foldLeft(root)(_.resolve(_)) + private[this] def extractSecuritySchemes[L <: LA, F[_]]( + spec: OpenAPI, + prefixes: List[String] + )(implicit Sw: SwaggerTerms[L, F], Sc: LanguageTerms[L, F]): F[Map[String, SecurityScheme[L]]] = { + import Sw._ + import Sc._ + + Tracker(spec) + .downField("components", _.getComponents) + .flatDownField("securitySchemes", _.getSecuritySchemes) + .indexedDistribute + .value + .flatTraverse { case (schemeName, scheme) => + val typeName = CustomTypeName(scheme, prefixes) + for { + tpe <- typeName.fold(Option.empty[L#Type].pure[F])(x => parseType(Tracker.cloneHistory(scheme, x))) + parsedScheme <- scheme.downField("type", _.getType).unwrapTracker.traverse { + case SwSecurityScheme.Type.APIKEY => extractApiKeySecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] + case SwSecurityScheme.Type.HTTP => extractHttpSecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] + case SwSecurityScheme.Type.OPENIDCONNECT => extractOpenIdConnectSecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] + case SwSecurityScheme.Type.OAUTH2 => extractOAuth2SecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] + case SwSecurityScheme.Type.MUTUALTLS => extractMutualTLSSecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] + } + } yield parsedScheme.toList.map(scheme => schemeName -> scheme) + } + .map(_.toMap) + } + def prepareDefinitions[L <: LA, F[_]]( kind: CodegenTarget, context: Context, @@ -82,7 +112,7 @@ object Common { requestBodies <- extractCommonRequestBodies(components) routes <- extractOperations(paths, requestBodies, globalSecurityRequirements) prefixes <- Cl.vendorPrefixes() - securitySchemes <- SwaggerUtil.extractSecuritySchemes(spec.unwrapTracker, prefixes) + securitySchemes <- extractSecuritySchemes(spec.unwrapTracker, prefixes) classNamedRoutes <- routes.traverse(route => getClassName(route.operation, prefixes, context.tagsBehaviour).map(_ -> route)) groupedRoutes = classNamedRoutes .groupMap(_._1)(_._2) diff --git a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala b/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala deleted file mode 100644 index 81bf1b9c02..0000000000 --- a/modules/core/src/main/scala/dev/guardrail/SwaggerUtil.scala +++ /dev/null @@ -1,41 +0,0 @@ -package dev.guardrail - -import io.swagger.v3.oas.models._ -import io.swagger.v3.oas.models.security.{ SecurityScheme => SwSecurityScheme } -import cats.syntax.all._ -import dev.guardrail.core.Tracker -import dev.guardrail.core.implicits._ -import dev.guardrail.terms.{ LanguageTerms, SecurityScheme, SwaggerTerms } -import dev.guardrail.core.extract.CustomTypeName -import dev.guardrail.core.extract.VendorExtension.VendorExtensible._ -import dev.guardrail.languages.LA - -object SwaggerUtil { - def extractSecuritySchemes[L <: LA, F[_]]( - spec: OpenAPI, - prefixes: List[String] - )(implicit Sw: SwaggerTerms[L, F], Sc: LanguageTerms[L, F]): F[Map[String, SecurityScheme[L]]] = { - import Sw._ - import Sc._ - - Tracker(spec) - .downField("components", _.getComponents) - .flatDownField("securitySchemes", _.getSecuritySchemes) - .indexedDistribute - .value - .flatTraverse { case (schemeName, scheme) => - val typeName = CustomTypeName(scheme, prefixes) - for { - tpe <- typeName.fold(Option.empty[L#Type].pure[F])(x => parseType(Tracker.cloneHistory(scheme, x))) - parsedScheme <- scheme.downField("type", _.getType).unwrapTracker.traverse { - case SwSecurityScheme.Type.APIKEY => extractApiKeySecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] - case SwSecurityScheme.Type.HTTP => extractHttpSecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] - case SwSecurityScheme.Type.OPENIDCONNECT => extractOpenIdConnectSecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] - case SwSecurityScheme.Type.OAUTH2 => extractOAuth2SecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] - case SwSecurityScheme.Type.MUTUALTLS => extractMutualTLSSecurityScheme(schemeName, scheme, tpe).widen[SecurityScheme[L]] - } - } yield parsedScheme.toList.map(scheme => schemeName -> scheme) - } - .map(_.toMap) - } -}