Skip to content
Open
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
3 changes: 3 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
# Scala Steward: Reformat with scalafmt 3.7.14
d389b41fac321833b103ba17f86fcb3e209f5596

# Scala Steward: Reformat with scalafmt 3.10.7
993cc9e62296f90555cf351846d9b61789c9e934
2 changes: 1 addition & 1 deletion .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version="3.7.17"
version="3.10.7"

project.git = true

Expand Down
6 changes: 3 additions & 3 deletions modules/cli/src/main/scala/dev/guardrail/cli/CLICommon.scala
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ trait CLICommon extends GuardrailRunner {
def Return(x: To): Target[Either[From, To]] = Target.pure(Either.right(x))
def Bail(x: Error): Target[Either[From, To]] = Target.raiseError(x)
for {
_ <- debug(s"Processing: ${rest.take(5).mkString(" ")}${if (rest.length > 3) "..." else ""} of ${rest.length}")
_ <- debug(s"Processing: ${rest.take(5).mkString(" ")}${if (rest.length > 3) "..." else ""} of ${rest.length}")
step <- pair match {
case (already, Nil) =>
debug("Finished") >> Return(already)
case (Nil, xs @ (_ :: _)) => Continue((empty :: Nil, xs))
case (Nil, xs @ (_ :: _)) => Continue((empty :: Nil, xs))
case (sofar :: already, "--defaults" :: xs) =>
Continue((empty.withDefaults(true) :: sofar :: already, xs))
case (sofar :: already, "--client" :: xs) =>
Expand Down Expand Up @@ -187,7 +187,7 @@ trait CLICommon extends GuardrailRunner {
guardrailRunner(language, args.toArray)
}

val fallback = List.empty[Path]
val fallback = List.empty[Path]
val paths: List[Path] = result
.fold(
{
Expand Down
2 changes: 1 addition & 1 deletion modules/cli/src/test/scala/CLICommonSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class CLICommonSpec extends AnyFunSuite with SwaggerSpecRunner with Matchers wit
parseArgsLang("scala", args)
def parseArgsLang(language: String, args: Array[String]): Vector[String] = {
val state = new AtomicReference(Vector.empty[String])
val impl = new CLICommon {
val impl = new CLICommon {
val AnsiColor = new {
val BLUE: String = ""
val BOLD: String = ""
Expand Down
6 changes: 3 additions & 3 deletions modules/core/src/main/scala/dev/guardrail/Common.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ object Common {
.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)))
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]]
Expand Down Expand Up @@ -105,7 +105,7 @@ object Common {
.flatMap(url => Option(new URI(url).getPath))
.filter(_ != "/")

paths = spec.downField("paths", _.getPaths)
paths = spec.downField("paths", _.getPaths)
globalSecurityRequirements = NonEmptyList
.fromList(spec.downField("security", _.getSecurity).indexedDistribute)
.flatMap(SecurityRequirements(_, SecurityRequirements.Global))
Expand Down Expand Up @@ -196,7 +196,7 @@ object Common {
servers.flatTraverse(writeServer(pkgPath, formattedPkgName, customImports, frameworkImplicitNames, filteredDtoComponents, _))
).mapN(_ ++ _)

implicits <- renderImplicits(pkgPath, formattedPkgName, frameworkImports, protocolImports, customImports)
implicits <- renderImplicits(pkgPath, formattedPkgName, frameworkImports, protocolImports, customImports)
frameworkImplicitsFile <- frameworkImplicits.fold(Option.empty[WriteTree].pure[F]) { case (name, defn) =>
renderFrameworkImplicits(pkgPath, formattedPkgName, frameworkImports, frameworkImplicitNames.filterNot(_ == name), protocolImports, defn, name)
.map(Option.apply)
Expand Down
14 changes: 7 additions & 7 deletions modules/core/src/main/scala/dev/guardrail/Target.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ object Target {
def pushLogger(value: StructuredLogger): Target[Unit] = new TargetValue((), if (loggerEnabled.get) value else StructuredLogger.Empty)
def pure[T](x: T): Target[T] = new TargetValue(x, StructuredLogger.Empty)

def raiseError[T](x: Error): Target[T] = new TargetError(x, StructuredLogger.Empty)
def raiseUserError[T](x: String): Target[T] = raiseError(UserError(x))
def raiseException[T](x: String): Target[T] = raiseError(RuntimeFailure(x))
def raiseError[T](x: Error): Target[T] = new TargetError(x, StructuredLogger.Empty)
def raiseUserError[T](x: String): Target[T] = raiseError(UserError(x))
def raiseException[T](x: String): Target[T] = raiseError(RuntimeFailure(x))
def fromEither[T](x: Either[Error, T]): Target[T] =
x.fold[Target[T]](err => new TargetError(err, StructuredLogger.Empty), value => new TargetValue(value, StructuredLogger.Empty))
def fromOption[T](x: Option[T], default: => Error): Target[T] =
Expand Down Expand Up @@ -68,13 +68,13 @@ object Target {
}

object log {
def push(name: String): Target[Unit] = pushLogger(StructuredLogger.push(name))
def pop: Target[Unit] = pushLogger(StructuredLogger.pop)
def push(name: String): Target[Unit] = pushLogger(StructuredLogger.push(name))
def pop: Target[Unit] = pushLogger(StructuredLogger.pop)
def function[A](name: String): Target[A] => Target[A] = { func =>
(push(name) *> func) <* pop
}
def debug(message: String): Target[Unit] = pushLogger(StructuredLogger.debug(message))
def info(message: String): Target[Unit] = pushLogger(StructuredLogger.info(message))
def debug(message: String): Target[Unit] = pushLogger(StructuredLogger.debug(message))
def info(message: String): Target[Unit] = pushLogger(StructuredLogger.info(message))
def warning(message: String): Target[Unit] = {
println(message)
pushLogger(StructuredLogger.warning(message))
Expand Down
2 changes: 1 addition & 1 deletion modules/core/src/main/scala/dev/guardrail/WriteTree.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ object WriteTree {
for {
writeState <-
if (Files.exists(path)) {
val exists: Array[Byte] = Files.readAllBytes(path)
val exists: Array[Byte] = Files.readAllBytes(path)
val diffIdx: Option[Int] =
exists
.zip(data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class CoreTermInterp[L <: LA](
def extractGenerator(context: Context, vendorDefaultFramework: Option[String]) =
Target.log.function("extractGenerator") {
for {
_ <- Target.log.debug("Looking up framework")
_ <- Target.log.debug("Looking up framework")
framework <- NonEmptyList
.fromList(context.modules)
.toRight(context.framework)
Expand Down Expand Up @@ -107,7 +107,7 @@ class CoreTermInterp[L <: LA](
kind = args.kind
dtoPackage = args.dtoPackage
context = args.context
_ <- verifyPropertyRequirement(context.propertyRequirement)
_ <- verifyPropertyRequirement(context.propertyRequirement)
customImports <- args.imports
.traverse(x =>
for {
Expand All @@ -128,7 +128,7 @@ class CoreTermInterp[L <: LA](
_ <- Sw.log.debug("Running guardrail codegen")
formattedPkgName <- Sc.formatPackageName(pkgName)
definitionsPkgName <- Sc.fullyQualifyPackageName(formattedPkgName)
(proto, codegen) <- Common
(proto, codegen) <- Common
.prepareDefinitions[L, Target](
kind,
context,
Expand All @@ -137,7 +137,7 @@ class CoreTermInterp[L <: LA](
definitionsPkgName :+ "support"
)
protocolSupport <- Ps.generateSupportDefinitions()
result <- Common
result <- Common
.writePackage[L, Target](proto, codegen, context)(Paths.get(outputPath), formattedPkgName.toList, dtoPackage, customImports, protocolSupport)
} yield result
} catch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ class PathExtractor[L <: LA, T, TN <: T, ModelGeneratorType](
type P = Parser[(Option[TN], T)]
type LP = Parser[List[(Option[TN], T)]]

val plainString: Parser[String] = many(noneOf("{}/?")).map(_.mkString)
val plainNEString: Parser[String] = many1(noneOf("{}/?")).map(_.toList.mkString)
val stringSegment: P = plainNEString.map(s => (None, stringPath(s)))
val plainString: Parser[String] = many(noneOf("{}/?")).map(_.mkString)
val plainNEString: Parser[String] = many1(noneOf("{}/?")).map(_.toList.mkString)
val stringSegment: P = plainNEString.map(s => (None, stringPath(s)))
def regexSegment(implicit pathArgs: List[LanguageParameter[L]], modelGeneratorType: ModelGeneratorType): P =
(plainString ~ PathExtractor.variable ~ plainString).flatMap { case ((before, binding), after) =>
PathExtractor.lookupName[L, (Option[TN], T)](binding, pathArgs) { case param @ LanguageParameter(_, _, paramName, argName, _) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ object LazyResolvedType {
import Sw._
for {
formattedName <- formatTypeName(name)
resolved <- resolveType(formattedName, protocolElems)
resolved <- resolveType(formattedName, protocolElems)
.flatMap {
case RandomType(name, tpe) =>
liftType(tpe).map(Resolved[L](_, None, None, liftRawType(ReifiedRawType.unsafeEmpty)))
Expand Down Expand Up @@ -113,7 +113,7 @@ object ResolvedType {
protocolElems: List[StrictProtocolElems[L]]
)(implicit Sc: LanguageTerms[L, F], Cl: CollectionsLibTerms[L, F], Sw: OpenAPITerms[L, F]): F[Resolved[L]] =
for {
_ <- Sw.log.debug(s"value: ${value} in ${protocolElems.length} protocol elements")
_ <- Sw.log.debug(s"value: ${value} in ${protocolElems.length} protocol elements")
res <- value
.bimap(LazyResolvedType.lift[L, F](_, protocolElems), _.pure[F])
.merge
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ sealed trait StructuredLoggerInstances extends StructuredLoggerLowPriority {
for {
(init, last) <- xs.initLast
(head, tail) <- ys.uncons
combined <- ((last, head) match {
combined <- ((last, head) match {
case (StructuredLogBlock(lastLines), StructuredLogBlock(headLines)) =>
Some(StructuredLogBlock(lastLines ++ headLines))
case (_, _) => None
Expand All @@ -64,7 +64,7 @@ sealed trait StructuredLoggerInstances extends StructuredLoggerLowPriority {
}
}
implicit object StructuredLoggerMonoid extends Monoid[StructuredLogger] {
def empty: StructuredLogger = StructuredLogger(Chain.empty)
def empty: StructuredLogger = StructuredLogger(Chain.empty)
def combine(x: StructuredLogger, y: StructuredLogger): StructuredLogger = StructuredLogger((x.entries, y.entries) match {
case StructuredLogEntryCombine(combined) => combined
case (xs, ys) => Monoid[Chain[StructuredLogEntry]].combine(xs, ys)
Expand All @@ -81,15 +81,15 @@ sealed trait StructuredLoggerInstances extends StructuredLoggerLowPriority {
case ((acc, newHistory), StructuredLoggerReset) =>
(acc, Chain.empty)
case ((acc, newHistory), StructuredLogBlock(lines)) =>
val history = NonEmptyChain.fromChain[String](newHistory).getOrElse(NonEmptyChain("<root>"))
val history = NonEmptyChain.fromChain[String](newHistory).getOrElse(NonEmptyChain("<root>"))
val nextLines: Chain[(LogLevel, NonEmptyChain[String], String)] = lines
.filter(_._1 >= desiredLevel)
.map { case (level, message) => (level, history, message) }
(acc ++ nextLines, newHistory)
}
._1
.foldLeft((Chain.empty[String], Chain.empty[String])) { case ((lastHistory, messages), (level, history, message)) =>
val showFullHistory = true
val showFullHistory = true
def makePrefix(history: Vector[String]): String =
history.foldLeft(" ") { case (a, b) =>
(if (showFullHistory) {
Expand All @@ -101,7 +101,7 @@ sealed trait StructuredLoggerInstances extends StructuredLoggerLowPriority {

val historyVec = history.toChain.toVector
val commonPrefixLength = historyVec.length - lastHistory.toVector.zip(historyVec).takeWhile(((_: String) == (_: String)).tupled).length
val histories = if (!showFullHistory) {
val histories = if (!showFullHistory) {
(1 until commonPrefixLength).map(i => s"${level.show} ${makePrefix(historyVec.take(i))}")
} else Nil
val prefix = s"${level.show} ${makePrefix(historyVec)}: "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ trait HighPriorityTrackerEvidence extends LowPriorityTrackerEvidence {
implicit def optionalListConvincer[A]: Tracker.Convincer[Option[List[A]], List[A]] = Tracker.Convincer(_.getOrElse(List.empty[A]))
implicit def optionaljuCollectionConvincer[A]: Tracker.Convincer[Option[java.util.Collection[A]], List[A]] =
Tracker.Convincer(_.fold(List.empty[A])(_.asScala.toList))
implicit def optionalOptionConvincer[A]: Tracker.Convincer[Option[Option[A]], Option[A]] = Tracker.Convincer(_.flatten)
implicit def optionalOptionConvincer[A]: Tracker.Convincer[Option[Option[A]], Option[A]] = Tracker.Convincer(_.flatten)
implicit def optionaljuMapConvincer[K, V]: Tracker.Convincer[Option[java.util.Map[K, V]], Mappish[List, K, V]] =
Tracker.Convincer(_.fold(Mappish(List.empty[(K, V)]))(x => Mappish(x.asScala.toList)))
implicit def optionalMapConvincer[K, V]: Tracker.Convincer[Option[Map[K, V]], Mappish[List, K, V]] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ object ModelResolver {
)
.orRefine { case arr: ArraySchema => arr }(arr =>
for {
items <- getItems(arr)
items <- getItems(arr)
dereferencedItems <- items
.downField("$ref", _.get$ref())
.indexedDistribute
Expand All @@ -107,7 +107,7 @@ object ModelResolver {
itemsRawFormat = dereferencedItems.downField("format", _.getFormat())
prefixes <- vendorPrefixes()
arrayType <- CustomArrayTypeName(arr, prefixes).flatTraverse(x => parseType(Tracker.cloneHistory(arr, x)))
res <- meta match {
res <- meta match {
case Right(core.Resolved(inner, dep, default, _)) =>
(liftVectorType(inner, arrayType), default.traverse(liftVectorTerm))
.mapN((t, d) =>
Expand Down Expand Up @@ -136,7 +136,7 @@ object ModelResolver {
}
prefixes <- vendorPrefixes()
mapType <- CustomMapTypeName(map, prefixes).flatTraverse(x => parseType(Tracker.cloneHistory(map, x)))
res <- rec match {
res <- rec match {
case Right(core.Resolved(inner, dep, _, rawType)) =>
liftMapType(inner, mapType).map(t => Right(core.Resolved[L](t, dep, None, ReifiedRawType.ofMap(rawType))))
case Left(x: core.DeferredMap[L]) => embedMap(x, mapType).map(Left(_))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ abstract class AbstractModule[L <: LA] {
} match {
case (_, Nil) => Target.raiseError(MissingModule(section, (first :: rest.toList).map(_._1)))
case (rest, value :: Nil) => value.map((rest, _))
case (rest, a :: b :: _) =>
case (rest, a :: b :: _) =>
Target.raiseError(ModuleConflict(section))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ object LanguageParameter {
for {
parameters <- params.traverse(fromParameter(protocolElems, components))
counts <- parameters.traverse(param => extractTermName(param.paramName)).map(_.groupBy(identity).view.mapValues(_.length).toMap)
result <- parameters.traverse { param =>
result <- parameters.traverse { param =>
extractTermName(param.paramName).flatMap { name =>
if (counts.getOrElse(name, 0) > 1) {
pureTermName(param.argName.value).flatMap { escapedName =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class OpenAPIGenerator[L <: LA] extends OpenAPITerms[L, Target] {
globalSecurityRequirements: Option[SecurityRequirements]
): Target[List[RouteMeta]] =
Target.log.function("extractOperations")(for {
_ <- Target.log.debug(s"Args: ${paths.unwrapTracker.value.map { case (a, b) => (a, b.showNotNull) }} (${paths.showHistory})")
_ <- Target.log.debug(s"Args: ${paths.unwrapTracker.value.map { case (a, b) => (a, b.showNotNull) }} (${paths.showHistory})")
routes <- paths.indexedCosequence.value.flatTraverse { case (pathStr, path) =>
for {
operationMap <- path
Expand Down Expand Up @@ -183,7 +183,7 @@ class OpenAPIGenerator[L <: LA] extends OpenAPITerms[L, Target] {

className = ClassPrefix(operation, vendorPrefixes) match {
case cls @ Some(_) => cls.toList
case None =>
case None =>
val pkg = PackageName(operation, vendorPrefixes)
.map(_.split('.').toVector)
.orElse(
Expand Down Expand Up @@ -284,7 +284,7 @@ class OpenAPIGenerator[L <: LA] extends OpenAPITerms[L, Target] {
.refine[Target[Tracker[A]]] { case extract(name) => name }(name =>
for {
components <- components.raiseErrorIfEmpty("Attempting to dereference a $ref, but no components defined")
result <- components
result <- components
.downField(label, proj)
.map(_.value.toMap.get(name.unwrapTracker))
.raiseErrorIfEmpty(s"Attempting to dereference a $$ref, but no object found at the specified pointer")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import cats.implicits._

object ModuleLoadResult {
implicit val moduleLoadResultApplicative: Applicative[ModuleLoadResult] = new Applicative[ModuleLoadResult] {
def pure[A](x: A): ModuleLoadResult[A] = new ModuleLoadSuccess(Set.empty, Set.empty, x)
def pure[A](x: A): ModuleLoadResult[A] = new ModuleLoadSuccess(Set.empty, Set.empty, x)
def ap[A, B](ff: ModuleLoadResult[A => B])(fa: ModuleLoadResult[A]): ModuleLoadResult[B] = ff match {
case f: ModuleLoadSuccess[A => B] =>
fa match {
Expand All @@ -35,7 +35,7 @@ object ModuleLoadResult {
}

implicit def moduleLoadResultSemigroup[A]: Monoid[ModuleLoadResult[A]] = new Monoid[ModuleLoadResult[A]] {
def empty: ModuleLoadResult[A] = ModuleLoadFailed.of(Set.empty, Set.empty, Map.empty)
def empty: ModuleLoadResult[A] = ModuleLoadFailed.of(Set.empty, Set.empty, Map.empty)
def combine(a: ModuleLoadResult[A], b: ModuleLoadResult[A]): ModuleLoadResult[A] =
(a, b) match {
case (a: ModuleLoadConflict, _) =>
Expand Down Expand Up @@ -84,13 +84,13 @@ object ModuleLoadResult {
}
}

private[this] def extractLabel[A](descriptor: ModuleDescriptor[A]): Set[String] = Set(descriptor._1)
private[this] def extractLabel[A](descriptor: ModuleDescriptor[A]): Set[String] = Set(descriptor._1)
private[this] def extractChoices[A](descriptor: ModuleDescriptor[A]): Map[String, Set[String]] = {
val (label, mappings) = descriptor
Map(label -> mappings.flatMap(_.keys).toSet)
}

def emitDefault[A](a: A): Set[String] => ModuleLoadResult[A] = _ => new ModuleLoadSuccess[A](Set.empty, Set.empty, a)
def emitDefault[A](a: A): Set[String] => ModuleLoadResult[A] = _ => new ModuleLoadSuccess[A](Set.empty, Set.empty, a)
def forProduct1[A, Z](a: ModuleDescriptor[A])(combine: A => Z): Set[String] => ModuleLoadResult[Z] =
wrapper(module => work[A](a)(module))(_.map(combine)).map(_.getOrElse(ModuleLoadFailed.of(Set.empty, Set.empty, extractChoices(a))))
def forProduct2[A, B, Z](a: ModuleDescriptor[A], b: ModuleDescriptor[B])(combine: (A, B) => Z): Set[String] => ModuleLoadResult[Z] =
Expand Down
Loading
Loading