Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify plugin abi #1893

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 20 additions & 23 deletions modules/cli/src/main/scala/dev/guardrail/cli/CLICommon.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package dev.guardrail.cli

import cats.FlatMap
import cats.data.NonEmptyList
import cats.syntax.all._
import java.nio.file.Path
import scala.language.reflectiveCalls
Expand All @@ -20,7 +19,7 @@ object CommandLineResult {

trait CLICommon extends GuardrailRunner {
def putErrLn(string: String): Unit
def guardrailRunner: Map[String, NonEmptyList[Args]] => Target[List[java.nio.file.Path]]
def guardrailRunner(language: String, args: Array[Args]): Target[List[java.nio.file.Path]]

def AnsiColor: {
val BLUE: String
Expand Down Expand Up @@ -94,7 +93,7 @@ trait CLICommon extends GuardrailRunner {
def expandTilde(path: String): String =
path.replaceFirst("^~", System.getProperty("user.home"))
val defaultArgs =
Args.empty.copy(context = Args.empty.context, defaults = true)
Args.empty.withDefaults(true)

type From = (List[Args], List[String])
type To = List[Args]
Expand All @@ -106,7 +105,7 @@ trait CLICommon extends GuardrailRunner {
.filter(_.defaults)
.lastOption
.getOrElse(defaultArgs)
.copy(defaults = false)
.withDefaults(false)
def Continue(x: From): Target[Either[From, To]] = Target.pure(Either.left(x))
def Return(x: To): Target[Either[From, To]] = Target.pure(Either.right(x))
def Bail(x: Error): Target[Either[From, To]] = Target.raiseError(x)
Expand All @@ -117,35 +116,35 @@ trait CLICommon extends GuardrailRunner {
debug("Finished") >> Return(already)
case (Nil, xs @ (_ :: _)) => Continue((empty :: Nil, xs))
case (sofar :: already, "--defaults" :: xs) =>
Continue((empty.copy(defaults = true) :: sofar :: already, xs))
Continue((empty.withDefaults(true) :: sofar :: already, xs))
case (sofar :: already, "--client" :: xs) =>
Continue((empty :: sofar :: already, xs))
case (sofar :: already, "--server" :: xs) =>
Continue((empty.copy(kind = CodegenTarget.Server) :: sofar :: already, xs))
Continue((empty.withKind(CodegenTarget.Server) :: sofar :: already, xs))
case (sofar :: already, "--models" :: xs) =>
Continue((empty.copy(kind = CodegenTarget.Models) :: sofar :: already, xs))
Continue((empty.withKind(CodegenTarget.Models) :: sofar :: already, xs))
case (sofar :: already, "--framework" :: value :: xs) =>
Continue((sofar.copyContext(framework = Some(value)) :: already, xs))
Continue((sofar.modifyContext(_.withFramework(Some(value))) :: already, xs))
case (sofar :: already, "--help" :: xs) =>
Continue((sofar.copy(printHelp = true) :: already, List.empty))
Continue((sofar.withPrintHelp(true) :: already, List.empty))
case (sofar :: already, "--specPath" :: value :: xs) =>
Continue((sofar.copy(specPath = Option(expandTilde(value))) :: already, xs))
Continue((sofar.withSpecPath(Option(expandTilde(value))) :: already, xs))
case (sofar :: already, "--tracing" :: xs) =>
Continue((sofar.copyContext(tracing = true) :: already, xs))
Continue((sofar.modifyContext(_.withTracing(true)) :: already, xs))
case (sofar :: already, "--outputPath" :: value :: xs) =>
Continue((sofar.copy(outputPath = Option(expandTilde(value))) :: already, xs))
Continue((sofar.withOutputPath(Option(expandTilde(value))) :: already, xs))
case (sofar :: already, "--packageName" :: value :: xs) =>
Continue((sofar.copy(packageName = Option(value.trim.split('.').toList)) :: already, xs))
Continue((sofar.withPackageName(Option(value.trim.split('.').toList)) :: already, xs))
case (sofar :: already, "--dtoPackage" :: value :: xs) =>
Continue((sofar.copy(dtoPackage = value.trim.split('.').toList) :: already, xs))
Continue((sofar.withDtoPackage(value.trim.split('.').toList) :: already, xs))
case (sofar :: already, "--import" :: value :: xs) =>
Continue((sofar.copy(imports = sofar.imports :+ value) :: already, xs))
Continue((sofar.withImports(sofar.imports :+ value) :: already, xs))
case (sofar :: already, "--module" :: value :: xs) =>
Continue((sofar.copyContext(modules = sofar.context.modules :+ value) :: already, xs))
Continue((sofar.modifyContext(_.withModules(sofar.context.modules :+ value)) :: already, xs))
case (sofar :: already, "--custom-extraction" :: xs) =>
Continue((sofar.copyContext(customExtraction = true) :: already, xs))
Continue((sofar.modifyContext(_.withCustomExtraction(true)) :: already, xs))
case (sofar :: already, "--package-from-tags" :: xs) =>
Continue((sofar.copyContext(tagsBehaviour = Context.PackageFromTags) :: already, xs))
Continue((sofar.modifyContext(_.withTagsBehaviour(TagsBehaviour.PackageFromTags)) :: already, xs))
case (sofar :: already, (arg @ "--optional-encode-as") :: value :: xs) =>
for {
propertyRequirement <- parseOptionalProperty(arg.drop(2), value)
Expand All @@ -159,7 +158,7 @@ trait CLICommon extends GuardrailRunner {
case (sofar :: already, (arg @ "--auth-implementation") :: value :: xs) =>
for {
auth <- parseAuthImplementation(arg, value)
res <- Continue((sofar.copyContext(authImplementation = auth) :: already, xs))
res <- Continue((sofar.modifyContext(_.withAuthImplementation(auth)) :: already, xs))
} yield res
case (_, unknown) =>
debug("Unknown argument") >> Bail(UnknownArguments(unknown))
Expand All @@ -179,15 +178,13 @@ trait CLICommon extends GuardrailRunner {

level.foreach(_ => Target.loggerEnabled.set(true))

val coreArgs = parseArgs(newArgs).map(NonEmptyList.fromList(_))

implicit val logLevel: LogLevel = level
.flatMap(level => LogLevels.members.find(_.level == level.toLowerCase))
.getOrElse(LogLevels.Warning)

val result = coreArgs
val result = parseArgs(newArgs)
.flatMap { args =>
guardrailRunner(args.map(language -> _).toMap)
guardrailRunner(language, args.toArray)
}

val fallback = List.empty[Path]
Expand Down
57 changes: 0 additions & 57 deletions modules/core/src/main/scala/dev/guardrail/Args.scala

This file was deleted.

29 changes: 0 additions & 29 deletions modules/core/src/main/scala/dev/guardrail/Context.scala

This file was deleted.

7 changes: 7 additions & 0 deletions modules/core/src/main/scala/dev/guardrail/TagsBehavior.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package dev.guardrail

sealed trait TagsBehaviour
object TagsBehaviour {
case object PackageFromTags extends TagsBehaviour
case object TagsAreIgnored extends TagsBehaviour
}
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ class OpenAPIGenerator[L <: LA] extends OpenAPITerms[L, Target] {
override def extractMutualTLSSecurityScheme(schemeName: String, securityScheme: Tracker[SwSecurityScheme], tpe: Option[L#Type]) =
Target.pure(MutualTLSSecurityScheme[L](tpe))

override def getClassName(operation: Tracker[Operation], vendorPrefixes: List[String], tagBehaviour: Context.TagsBehaviour) =
override def getClassName(operation: Tracker[Operation], vendorPrefixes: List[String], tagBehaviour: TagsBehaviour) =
Target.log.function("getClassName")(for {
_ <- Target.log.debug(s"Args: ${operation.unwrapTracker.showNotNull}")

Expand All @@ -188,15 +188,15 @@ class OpenAPIGenerator[L <: LA] extends OpenAPITerms[L, Target] {
.map(_.split('.').toVector)
.orElse(
tagBehaviour match {
case Context.PackageFromTags =>
case TagsBehaviour.PackageFromTags =>
operation
.downField("tags", _.getTags)
.toNel
.indexedCosequence
.map { tags =>
tags.unwrapTracker.toList
}
case Context.TagsAreIgnored =>
case TagsBehaviour.TagsAreIgnored =>
None
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,23 @@ import cats.data.NonEmptyList
import cats.syntax.all._
import scala.io.AnsiColor

import dev.guardrail.{ Args, MissingDependency, ReadSpec, Target, WriteTree }
import dev.guardrail.{ Args, MissingDependency, NoArgsSpecified, ReadSpec, Target, WriteTree }
import dev.guardrail.core.StructuredLogger
import dev.guardrail.generators.spi.CoreTermsLoader

trait GuardrailRunner {
def guardrailRunner: Map[String, NonEmptyList[Args]] => Target[List[java.nio.file.Path]] = { tasks =>
runLanguages(tasks)
.flatMap(
_.flatTraverse(rs =>
ReadSpec
.readSpec(rs)
.flatMap(_.traverse(WriteTree.writeTree))
.leftFlatMap(value =>
Target.pushLogger(StructuredLogger.error(s"${AnsiColor.RED}Error in ${rs.path}${AnsiColor.RESET}")) *> Target.raiseError[List[Path]](value)
)
.productL(Target.pushLogger(StructuredLogger.reset))
)
abstract class GuardrailRunner {
def guardrailRunner(language: String, args: Array[Args]): Target[List[Path]] =
for {
args <- Target.fromOption(NonEmptyList.fromList(args.toList), NoArgsSpecified)
coreTermsLoader <- CoreTermsLoader.load(language, args, MissingDependency(s"${language}-support"))
result <- coreTermsLoader.toList.flatTraverse(rs =>
ReadSpec
.readSpec(rs)
.flatMap(_.traverse(WriteTree.writeTree))
.leftFlatMap(value =>
Target.pushLogger(StructuredLogger.error(s"${AnsiColor.RED}Error in ${rs.path}${AnsiColor.RESET}")) *> Target.raiseError[List[Path]](value)
)
.productL(Target.pushLogger(StructuredLogger.reset))
)
.map(_.distinct)
}

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"))
.map(_.toList)
}
} yield result
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ abstract class OpenAPITerms[L <: LA, F[_]] {
def extractOpenIdConnectSecurityScheme(schemeName: String, securityScheme: Tracker[SwSecurityScheme], tpe: Option[L#Type]): F[OpenIdConnectSecurityScheme[L]]
def extractOAuth2SecurityScheme(schemeName: String, securityScheme: Tracker[SwSecurityScheme], tpe: Option[L#Type]): F[OAuth2SecurityScheme[L]]
def extractMutualTLSSecurityScheme(schemeName: String, securityScheme: Tracker[SwSecurityScheme], tpe: Option[L#Type]): F[MutualTLSSecurityScheme[L]]
def getClassName(operation: Tracker[Operation], vendorPrefixes: List[String], tagBehaviour: Context.TagsBehaviour): F[List[String]]
def getClassName(operation: Tracker[Operation], vendorPrefixes: List[String], tagBehaviour: TagsBehaviour): F[List[String]]
def getParameterName(parameter: Tracker[Parameter]): F[String]
def getParameterSchema(parameter: Tracker[Parameter], components: Tracker[Option[Components]]): F[Tracker[SchemaProjection]]
def getRefParameterRef(parameter: Tracker[Parameter]): F[Tracker[String]]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package core.issues

import com.github.javaparser.ast.Node
import dev.guardrail.Context
import dev.guardrail.{ Context, TagsBehaviour }
import dev.guardrail.generators.java.JavaGeneratorMappings.javaInterpreter
import dev.guardrail.generators.{ Clients, Server, Servers }
import org.scalactic.source
Expand Down Expand Up @@ -84,7 +84,7 @@ class Issue314 extends AnyFunSpec with Matchers with SwaggerSpecRunner {
def verifyClient(config: String, expectedClassPrefix: String)(implicit pos: source.Position): Unit = {

val (_, Clients(clt :: _, _), _) =
runSwaggerSpec(javaInterpreter)(swagger(config))(Context.empty.copy(tagsBehaviour = Context.PackageFromTags), "dropwizard")
runSwaggerSpec(javaInterpreter)(swagger(config))(Context.empty.withTagsBehaviour(TagsBehaviour.PackageFromTags), "dropwizard")
val cls = clt.client.head.getOrElse(fail("Client does not contain a ClassDefinition"))

verifyNode(cls, client(expectedClassPrefix))
Expand All @@ -95,7 +95,7 @@ class Issue314 extends AnyFunSpec with Matchers with SwaggerSpecRunner {
_,
_,
Servers(Server(_, _, genHandler, genResource :: Nil) :: Nil, _)
) = runSwaggerSpec(javaInterpreter)(swagger(config))(Context.empty.copy(tagsBehaviour = Context.PackageFromTags), "dropwizard")
) = runSwaggerSpec(javaInterpreter)(swagger(config))(Context.empty.withTagsBehaviour(TagsBehaviour.PackageFromTags), "dropwizard")

verifyNode(genHandler, handler(expectedClassPrefix))
verifyNode(genResource, resource(expectedClassPrefix))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package core.issues

import dev.guardrail.generators.scala.ScalaGeneratorMappings.scalaInterpreter
import dev.guardrail.generators.scala.syntax.companionForStaticDefns
import dev.guardrail.Context
import dev.guardrail.{ Context, TagsBehaviour }
import dev.guardrail.generators.{ Client, Clients, Server, Servers }
import org.scalactic.source
import org.scalatest.funspec.AnyFunSpec
Expand Down Expand Up @@ -150,7 +150,7 @@ class Issue314 extends AnyFunSpec with Matchers with SwaggerSpecRunner {
_,
Clients(Client(_, _, _, staticDefns, cls, _) :: _, Nil),
_
) = runSwaggerSpec(scalaInterpreter)(swagger(config))(Context.empty.copy(tagsBehaviour = Context.PackageFromTags), "akka-http")
) = runSwaggerSpec(scalaInterpreter)(swagger(config))(Context.empty.withTagsBehaviour(TagsBehaviour.PackageFromTags), "akka-http")
val cmp = companionForStaticDefns(staticDefns)

verifyTree(cls.head.value, client(expectedClassPrefix))
Expand All @@ -162,7 +162,7 @@ class Issue314 extends AnyFunSpec with Matchers with SwaggerSpecRunner {
_,
_,
Servers(Server(_, _, genHandler, genResource :: Nil) :: Nil, Nil)
) = runSwaggerSpec(scalaInterpreter)(swagger(config))(Context.empty.copy(tagsBehaviour = Context.PackageFromTags), "akka-http")
) = runSwaggerSpec(scalaInterpreter)(swagger(config))(Context.empty.withTagsBehaviour(TagsBehaviour.PackageFromTags), "akka-http")

verifyTree(genHandler, handler(expectedClassPrefix))
verifyTree(genResource, resource(expectedClassPrefix))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ class AkkaHttpClientGeneratorTest extends AnyFunSuite with Matchers with Swagger
_,
Clients(List(Client(tags, className, _, staticDefns, cls, _)), Nil),
_
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(framework = Some("akka-http"), tracing = true), "akka-http")
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.withFramework(Some("akka-http")).withTracing(true), "akka-http")
val cmp = companionForStaticDefns(staticDefns)

tags should equal(Seq("store"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ class AkkaHttpServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunne
_,
_,
Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil)
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(tracing = true), "akka-http")
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.withTracing(true), "akka-http")

val handler = q"""
trait StoreHandler {
Expand Down Expand Up @@ -404,7 +404,7 @@ class AkkaHttpServerTest extends AnyFunSuite with Matchers with SwaggerSpecRunne
_,
_,
Servers(Server(pkg, extraImports, genHandler, genResource :: Nil) :: Nil, Nil)
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(customExtraction = true), "akka-http")
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.withCustomExtraction(true), "akka-http")

val handler = q"""
trait StoreHandler[-E] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class AkkaHttpClientTracingTest extends AnyFunSuite with Matchers with SwaggerSp
|""".stripMargin

val (_, Clients(Client(_, _, _, _, cls, _) :: _, Nil), _) =
runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(tracing = true), "akka-http")
runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.withTracing(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) {
Expand Down Expand Up @@ -91,7 +91,7 @@ class AkkaHttpClientTracingTest extends AnyFunSuite with Matchers with SwaggerSp
_,
Clients(Client(tags, className, _, _, cls, _) :: _, Nil),
_
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.copy(tracing = true), "akka-http")
) = runSwaggerSpec(scalaInterpreter)(spec)(Context.empty.withTracing(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) {
Expand Down
Loading