Skip to content

Commit

Permalink
misc: upgrade to ktlint v1.3.0 (#1108)
Browse files Browse the repository at this point in the history
  • Loading branch information
lauzadis committed Jun 27, 2024
1 parent 86e012c commit 920fc71
Show file tree
Hide file tree
Showing 149 changed files with 1,147 additions and 830 deletions.
5 changes: 5 additions & 0 deletions .changes/8b15116b-2008-4176-bb37-a6e2f30eda08.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"id": "8b15116b-2008-4176-bb37-a6e2f30eda08",
"type": "misc",
"description": "Upgrade to ktlint v1.3.0"
}
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
[*.{kt,kts}]
ktlint_code_style = intellij_idea

# ktlint rules to disable
ktlint_standard_no-wildcard-imports = disabled
ktlint_standard_filename = disabled
ktlint_standard_backing-property-naming = disabled

# enable trailing commas per JetBrains recommendation
# (https://kotlinlang.org/docs/coding-conventions.html#trailing-commas)
Expand Down
4 changes: 1 addition & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ out/
# Java/Kotlin
# Compiled class file
*.class
*.klib

# Log file
*.log
Expand Down Expand Up @@ -44,8 +45,5 @@ gradle-app.setting
# Cache of project
.gradletasknamecache

# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties

# MacOS
.DS_Store
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import software.amazon.smithy.model.shapes.ShapeId
* @inheritDoc
* @see AwsHttpBindingProtocolGenerator
*/
@Suppress("ktlint:standard:class-naming")
class AwsJson1_0 : JsonHttpBindingProtocolGenerator() {
override val protocol: ShapeId = AwsJson1_0Trait.ID
override val supportsJsonNameTrait: Boolean = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import software.amazon.smithy.model.shapes.ShapeId
* @inheritDoc
* @see AwsHttpBindingProtocolGenerator
*/
@Suppress("ktlint:standard:class-naming")
class AwsJson1_1 : JsonHttpBindingProtocolGenerator() {
override val protocol: ShapeId = AwsJson1_1Trait.ID
override val supportsJsonNameTrait: Boolean = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import software.amazon.smithy.model.shapes.*
import software.amazon.smithy.model.traits.HttpTrait
import software.amazon.smithy.model.traits.TimestampFormatTrait

private const val QueryContentType: String = "application/x-www-form-urlencoded"
private const val QUERY_CONTENT_TYPE: String = "application/x-www-form-urlencoded"

abstract class QueryHttpBindingProtocolGenerator : AwsHttpBindingProtocolGenerator() {
override val defaultTimestampFormat: TimestampFormatTrait.Format = TimestampFormatTrait.Format.DATE_TIME
Expand All @@ -33,7 +33,7 @@ abstract class QueryHttpBindingProtocolGenerator : AwsHttpBindingProtocolGenerat
val queryMiddleware = listOf(
// ensure content-type gets set
// see: https://awslabs.github.io/smithy/1.0/spec/aws/aws-query-protocol.html#protocol-behavior
MutateHeadersMiddleware(addMissingHeaders = mapOf("Content-Type" to QueryContentType)),
MutateHeadersMiddleware(addMissingHeaders = mapOf("Content-Type" to QUERY_CONTENT_TYPE)),
)

return middleware + queryMiddleware
Expand Down Expand Up @@ -69,7 +69,7 @@ abstract class QueryHttpBindingProtocolGenerator : AwsHttpBindingProtocolGenerat
class QueryBindingResolver(
model: Model,
service: ServiceShape,
) : StaticHttpBindingResolver(model, service, QueryHttpTrait, QueryContentType, TimestampFormatTrait.Format.DATE_TIME) {
) : StaticHttpBindingResolver(model, service, QueryHttpTrait, QUERY_CONTENT_TYPE, TimestampFormatTrait.Format.DATE_TIME) {
constructor(ctx: ProtocolGenerator.GenerationContext) : this(ctx.model, ctx.service)

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import java.util.logging.Logger
*/
class CodegenVisitor(context: PluginContext) : ShapeVisitor.Default<Unit>() {

private val LOGGER = Logger.getLogger(javaClass.name)
private val logger = Logger.getLogger(javaClass.name)
private val model: Model
private val settings = KotlinSettings.from(context.model, context.settings)
private val service: ServiceShape
Expand All @@ -47,16 +47,16 @@ class CodegenVisitor(context: PluginContext) : ShapeVisitor.Default<Unit>() {

init {
val classLoader = context.pluginClassLoader.orElse(javaClass.classLoader)
LOGGER.info("Discovering KotlinIntegration providers...")
logger.info("Discovering KotlinIntegration providers...")
integrations = ServiceLoader.load(KotlinIntegration::class.java, classLoader)
.onEach { integration -> LOGGER.info("Loaded KotlinIntegration: ${integration.javaClass.name}") }
.onEach { integration -> logger.info("Loaded KotlinIntegration: ${integration.javaClass.name}") }
.sortedBy(KotlinIntegration::order)
.toMutableList()

var resolvedModel = context.model
val disabledIntegrations = mutableListOf<KotlinIntegration>()

LOGGER.info("Preprocessing model")
logger.info("Preprocessing model")

// Model pre-processing:
// 1. Start with the model from the plugin context
Expand All @@ -65,7 +65,7 @@ class CodegenVisitor(context: PluginContext) : ShapeVisitor.Default<Unit>() {
// 4. Normalize the operations
for (integration in integrations) {
if (integration.enabledForService(resolvedModel, settings)) {
LOGGER.info("Enabled KotlinIntegration: ${integration.javaClass.name}")
logger.info("Enabled KotlinIntegration: ${integration.javaClass.name}")
resolvedModel = integration.preprocessModel(resolvedModel, settings)
} else {
disabledIntegrations.add(integration)
Expand Down Expand Up @@ -108,15 +108,15 @@ class CodegenVisitor(context: PluginContext) : ShapeVisitor.Default<Unit>() {
val protocolTrait = settings.resolveServiceProtocol(serviceIndex, service, generators.keys)
return generators[protocolTrait]
} catch (ex: UnresolvableProtocolException) {
LOGGER.warning("Unable to find protocol generator for ${service.id}: ${ex.message}")
logger.warning("Unable to find protocol generator for ${service.id}: ${ex.message}")
}
return null
}

fun execute() {
LOGGER.info("Generating Kotlin client for service ${settings.service}")
logger.info("Generating Kotlin client for service ${settings.service}")

LOGGER.info("Walking shapes from ${settings.service} to find shapes to generate")
logger.info("Walking shapes from ${settings.service} to find shapes to generate")
val modelWithoutTraits = ModelTransformer.create().getModelWithoutTraitShapes(model)
val serviceShapes = Walker(modelWithoutTraits).walkShapes(service)
serviceShapes.forEach { it.accept(this) }
Expand All @@ -132,16 +132,16 @@ class CodegenVisitor(context: PluginContext) : ShapeVisitor.Default<Unit>() {
writers,
)

LOGGER.info("[${service.id}] Generating unit tests for protocol $protocol")
logger.info("[${service.id}] Generating unit tests for protocol $protocol")
generateProtocolUnitTests(ctx)

LOGGER.info("[${service.id}] Generating service client for protocol $protocol")
logger.info("[${service.id}] Generating service client for protocol $protocol")
generateProtocolClient(ctx)

LOGGER.info("[${service.id}] Generating endpoint provider for protocol $protocol")
logger.info("[${service.id}] Generating endpoint provider for protocol $protocol")
generateEndpointsSources(ctx)

LOGGER.info("[${service.id}] Generating auth scheme provider for protocol $protocol")
logger.info("[${service.id}] Generating auth scheme provider for protocol $protocol")
generateAuthSchemeProvider(ctx)
}

Expand Down Expand Up @@ -171,7 +171,11 @@ class CodegenVisitor(context: PluginContext) : ShapeVisitor.Default<Unit>() {

override fun stringShape(shape: StringShape) {
// smithy will present both strings with legacy enum trait AND explicit (non-int) enum shapes in this manner
if (shape.hasTrait<@Suppress("DEPRECATION") software.amazon.smithy.model.traits.EnumTrait>()) {
if (shape.hasTrait<
@Suppress("DEPRECATION")
software.amazon.smithy.model.traits.EnumTrait,
>()
) {
writers.useShapeWriter(shape) { EnumGenerator(shape, symbolProvider.toSymbol(shape), it).render() }
}
}
Expand All @@ -186,7 +190,7 @@ class CodegenVisitor(context: PluginContext) : ShapeVisitor.Default<Unit>() {

override fun serviceShape(shape: ServiceShape) {
if (service != shape) {
LOGGER.fine("Skipping `${shape.id}` because it is not `${service.id}`")
logger.fine("Skipping `${shape.id}` because it is not `${service.id}`")
return
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ enum class DefaultValueSerializationMode(val value: String) {
*/
WHEN_DIFFERENT("whenDifferent"),
;

override fun toString(): String = value
companion object {
fun fromValue(value: String): DefaultValueSerializationMode =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class BuiltinPreprocessor : KotlinIntegration {
`FooString` is fine here though and need not be renamed as no type is
generated for it (it will end up as `kotlin.String`).
*/
*/
val shape = model.expectShape(it)
shape.isStructureShape || shape.isUnionShape || shape.isEnum
}.associate {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,12 @@ val Shape.isEnum: Boolean
* 2. The [legacy enum trait](https://awslabs.github.io/smithy/1.0/spec/core/constraint-traits.html#enum-trait) applied to a string shape
*/
val Shape.isStringEnumShape: Boolean
get() = isEnumShape || isStringShape && hasTrait<@Suppress("DEPRECATION") software.amazon.smithy.model.traits.EnumTrait>()
get() = isEnumShape ||
isStringShape &&
hasTrait<
@Suppress("DEPRECATION")
software.amazon.smithy.model.traits.EnumTrait,
>()

/**
* Test if a shape is an error.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ open class SymbolBuilder {
reference(refSymbol)
}

fun setProperty(key: String, value: Any) { builder.putProperty(key, value) }
fun removeProperty(key: String) { builder.removeProperty(key) }
fun setProperty(key: String, value: Any) {
builder.putProperty(key, value)
}
fun removeProperty(key: String) {
builder.removeProperty(key)
}
fun properties(block: PropertiesBuilder.() -> Unit) {
val propBuilder = object : PropertiesBuilder {
override fun set(key: String, value: Any) = setProperty(key, value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,14 @@ const val SYNTHETIC_NAMESPACE: String = "smithy.kotlin.synthetic"
* Must only be used as a runtime trait-only applied to shapes based on model processing
*/
class SyntheticClone private constructor(builder: Builder) :
AbstractTrait(ID, builder.sourceLocation), ToSmithyBuilder<SyntheticClone> {
AbstractTrait(ID, builder.sourceLocation),
ToSmithyBuilder<SyntheticClone> {
/**
* The original shape ID cloned from
*/
val archetype: ShapeId = requireNotNull(builder.archetype) { "Original ShapeId is required for SyntheticClone trait" }

override fun createNode(): Node {
throw CodegenException("attempted to serialize runtime only trait")
}
override fun createNode(): Node = throw CodegenException("attempted to serialize runtime only trait")

override fun toBuilder(): SmithyBuilder<SyntheticClone> {
val builder = Builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,10 @@ private fun Shape.asKotlinEnum(): KotlinEnum = when {
KotlinEnum(KotlinTypes.Int, variants)
}
isStringEnumShape -> {
val variants = expectTrait<@Suppress("DEPRECATION") software.amazon.smithy.model.traits.EnumTrait>()
val variants = expectTrait<
@Suppress("DEPRECATION")
software.amazon.smithy.model.traits.EnumTrait,
>()
.values
.sortedBy { it.name.orElse(it.value) }
.map {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,8 @@ fun renderJvmGradleBuild(

// Specifies if a given codegen operation is under a source or test scope
private enum class Scope {
SOURCE, TEST
SOURCE,
TEST,
}

private fun renderDependencies(writer: GradleWriter, scope: Scope, isKmp: Boolean, dependencies: List<KotlinDependency>) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,9 @@ class ExpressionGenerator(
private val writer: KotlinWriter,
private val rules: EndpointRuleSet,
private val functions: Map<String, Symbol>,
) : ExpressionVisitor<EndpointInfo?>, LiteralVisitor<EndpointInfo?>, TemplateVisitor<EndpointInfo?> {
) : ExpressionVisitor<EndpointInfo?>,
LiteralVisitor<EndpointInfo?>,
TemplateVisitor<EndpointInfo?> {
override fun visitLiteral(literal: Literal): EndpointInfo? = literal.accept(this as LiteralVisitor<EndpointInfo?>)

override fun visitRef(reference: Reference): EndpointInfo {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import java.util.logging.Logger
* Abstract implementation useful for all HTTP protocols
*/
abstract class HttpBindingProtocolGenerator : ProtocolGenerator {
private val LOGGER = Logger.getLogger(javaClass.name)
private val logger = Logger.getLogger(javaClass.name)

override val applicationProtocol: ApplicationProtocol = ApplicationProtocol.createDefaultHttpApplicationProtocol()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import java.util.*
import java.util.logging.Logger

enum class TestContainmentMode {
RUN_TESTS, EXCLUDE_TESTS
RUN_TESTS,
EXCLUDE_TESTS,
}

/**
Expand All @@ -36,7 +37,7 @@ class HttpProtocolTestGenerator(
// list of test ID's to ignore/skip
private val testDelta: TestMemberDelta = TestMemberDelta(setOf()),
) {
private val LOGGER = Logger.getLogger(javaClass.name)
private val logger = Logger.getLogger(javaClass.name)

/**
* Generates the API HTTP protocol tests defined in the smithy model.
Expand All @@ -56,7 +57,7 @@ class HttpProtocolTestGenerator(
val testClassName = "${testOperationName}RequestTest"
val testFilename = "$testClassName.kt"
ctx.delegator.useTestFileWriter(testFilename, ctx.settings.pkg.name) { writer ->
LOGGER.fine("Generating request protocol test cases for ${operation.id}")
logger.fine("Generating request protocol test cases for ${operation.id}")

// import package.models.*
writer.addImport("${ctx.settings.pkg.name}.model", "*")
Expand Down Expand Up @@ -84,7 +85,7 @@ class HttpProtocolTestGenerator(
val testClassName = "${testOperationName}ResponseTest"
val testFilename = "$testClassName.kt"
ctx.delegator.useTestFileWriter(testFilename, ctx.settings.pkg.name) { writer ->
LOGGER.fine("Generating response protocol test cases for ${operation.id}")
logger.fine("Generating response protocol test cases for ${operation.id}")

writer.addImport("${ctx.settings.pkg.name}.model", "*")
responseTestBuilder
Expand Down Expand Up @@ -114,7 +115,7 @@ class HttpProtocolTestGenerator(
// use the operation name + error name as the class name
val testClassName = "${opName}${error.defaultName(ctx.service)}Test"
ctx.delegator.useTestFileWriter(testFilename, ctx.settings.pkg.name) { writer ->
LOGGER.fine("Generating error protocol test cases for ${operation.id}")
logger.fine("Generating error protocol test cases for ${operation.id}")

writer.addImport("${ctx.settings.pkg.name}.model", "*")
errorTestBuilder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ import software.amazon.smithy.kotlin.codegen.model.hasStreamingMember
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.protocoltests.traits.HttpResponseTestCase

open class HttpProtocolUnitTestErrorGenerator protected constructor(builder: Builder) :
HttpProtocolUnitTestResponseGenerator(builder) {
open class HttpProtocolUnitTestErrorGenerator protected constructor(builder: Builder) : HttpProtocolUnitTestResponseGenerator(builder) {
val error: Shape = builder.error ?: throw CodegenException("builder did not set an error shape")

override val outputShape: Shape? = error
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ import software.amazon.smithy.protocoltests.traits.HttpMessageTestCase
* @param T Specific HttpMessageTestCase the protocol test generator is for.
*/
abstract class HttpProtocolUnitTestGenerator<T : HttpMessageTestCase>
protected constructor(builder: Builder<T>) {
protected constructor(
builder: Builder<T>,
) {

protected val ctx: ProtocolGenerator.GenerationContext = requireNotNull(builder.ctx) { "protocol generator ctx is required" }
protected val symbolProvider: SymbolProvider = requireNotNull(builder.symbolProvider) { "symbol provider is required" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait
/**
* Generates HTTP protocol unit tests for `httpRequestTest` cases
*/
open class HttpProtocolUnitTestRequestGenerator protected constructor(builder: Builder) :
HttpProtocolUnitTestGenerator<HttpRequestTestCase>(builder) {
open class HttpProtocolUnitTestRequestGenerator protected constructor(builder: Builder) : HttpProtocolUnitTestGenerator<HttpRequestTestCase>(builder) {

object ConfigureServiceClient : SectionId {
val Test: SectionKey<HttpRequestTestCase> = SectionKey("Test")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait
/**
* Generates HTTP protocol unit tests for `httpResponseTest` cases
*/
open class HttpProtocolUnitTestResponseGenerator protected constructor(builder: Builder) :
HttpProtocolUnitTestGenerator<HttpResponseTestCase>(builder) {
open class HttpProtocolUnitTestResponseGenerator protected constructor(builder: Builder) : HttpProtocolUnitTestGenerator<HttpResponseTestCase>(builder) {

object ConfigureServiceClient : SectionId {
val Test: SectionKey<HttpRequestTestCase> = SectionKey("Test")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,10 @@ class HttpStringValuesMapSerializer(
} else {
val nullCheck =
if (location == HttpBinding.Location.QUERY ||
memberTarget.hasTrait<@Suppress("DEPRECATION") software.amazon.smithy.model.traits.EnumTrait>()
memberTarget.hasTrait<
@Suppress("DEPRECATION")
software.amazon.smithy.model.traits.EnumTrait,
>()
) {
if (memberSymbol.isNullable) "input.$memberName != null" else ""
} else {
Expand All @@ -198,7 +201,10 @@ class HttpStringValuesMapSerializer(
val cond = defaultCheck(binding.member) ?: nullCheck

val suffix = when {
memberTarget.hasTrait<@Suppress("DEPRECATION") software.amazon.smithy.model.traits.EnumTrait>() -> {
memberTarget.hasTrait<
@Suppress("DEPRECATION")
software.amazon.smithy.model.traits.EnumTrait,
>() -> {
".value"
}
memberTarget.hasTrait<MediaTypeTrait>() -> {
Expand Down
Loading

0 comments on commit 920fc71

Please sign in to comment.