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

Add kotlin formatting plugin #27673

Merged
merged 1 commit into from
Sep 7, 2022
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
45 changes: 44 additions & 1 deletion build-parent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@
<artifactId>d3js</artifactId>
<version>${webjar.d3js.version}</version>
</dependency>
<dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>chartjs</artifactId>
<version>${webjar.chartjs.version}</version>
Expand Down Expand Up @@ -775,6 +775,49 @@
</build>
</profile>

<profile>
<id>format-kotlin</id>
<activation>
<activeByDefault>true</activeByDefault>
<property>
<name>!no-format</name>
</property>
<file>
<exists>src/main/kotlin</exists>
</file>
</activation>
<build>
<plugins>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>2.25.0</version>
<executions>
<execution>
<id>format-kotlin</id>
<phase>process-sources</phase>
<goals>
<goal>apply</goal>
</goals>
</execution>
</executions>

<configuration>
<kotlin>
<!--
<ktfmt>
<style>DEFAULT</style> &lt;!&ndash; optional, other options are DEFAULT, DROPBOX, GOOGLE and KOTLINLANG &ndash;&gt;
</ktfmt>
-->
<ktlint/>

</kotlin>
</configuration>
</plugin>
</plugins>
</build>
</profile>
Comment on lines +778 to +819
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need a different profile? Would it not be better to use the existing profiles?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm ok combining them but this one also looks for the existence of kotlin sources to activate. So it's not trying to do work most of the time. It might be a microoptimization but it made sense at the time. @gsmet?


<profile>
<id>release</id>
<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package org.acme

import java.io.IOException
import javax.enterprise.context.ApplicationScoped
import javax.websocket.*
import javax.websocket.server.PathParam
import javax.websocket.server.ServerEndpoint

@ServerEndpoint("/start-websocket/{name}")
@ApplicationScoped
@ServerEndpoint("/start-websocket/{name}")
class StartWebSocket {

@OnOpen
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ import javax.persistence.LockModeType
*
* @param Entity the entity type
*/
interface PanacheCompanion<Entity : PanacheEntityBase>: PanacheCompanionBase<Entity, Long>
interface PanacheCompanion<Entity : PanacheEntityBase> : PanacheCompanionBase<Entity, Long>

/**
* Defines methods to be used via the companion objects of entities.
*
* @param Entity the entity type
*/
interface PanacheCompanionBase<Entity : PanacheEntityBase, Id: Any> {
interface PanacheCompanionBase<Entity : PanacheEntityBase, Id : Any> {

/**
* Returns the [EntityManager] for the [Entity] for extra operations (eg. CriteriaQueries)
Expand Down Expand Up @@ -528,7 +528,6 @@ interface PanacheCompanionBase<Entity : PanacheEntityBase, Id: Any> {
@GenerateBridge
fun update(query: String, params: Parameters): Int = throw implementationInjectionMissing()


/**
* Flushes all pending changes to the database.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.quarkus.hibernate.orm.panache.kotlin


import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.MappedSuperclass
Expand All @@ -18,7 +17,7 @@ import javax.persistence.MappedSuperclass
* @see [PanacheEntityBase]
*/
@MappedSuperclass
open class PanacheEntity: PanacheEntityBase {
open class PanacheEntity : PanacheEntityBase {
/**
* The auto-generated ID field. This field is set by Hibernate ORM when this entity
* is persisted.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package io.quarkus.hibernate.orm.panache.kotlin

import com.fasterxml.jackson.annotation.JsonIgnore
import io.quarkus.hibernate.orm.panache.common.runtime.AbstractJpaOperations
import io.quarkus.hibernate.orm.panache.kotlin.runtime.KotlinJpaOperations.Companion.INSTANCE
import javax.json.bind.annotation.JsonbTransient
import javax.persistence.EntityManager

/**
* Represents an entity. If your Hibernate entities extend this class they gain auto-generated accessors
Expand All @@ -31,9 +29,9 @@ interface PanacheEntityBase {
/**
* Persist this entity in the database, if not already persisted. This will set your ID field if it is not already set.
*
* @see [PanacheEntityBase.isPersistent]
* @see [PanacheEntityBase.flush]
* @see [PanacheEntityBase.persistAndFlush]
* @see [PanacheEntityBase.isPersistent]
* @see [PanacheEntityBase.flush]
* @see [PanacheEntityBase.persistAndFlush]
*/
fun persist() {
INSTANCE.persist(this)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ import javax.persistence.NonUniqueResultException
*
* @param Entity The entity type being queried
*/
interface PanacheQuery<Entity: Any> {
interface PanacheQuery<Entity : Any> {
/**
* Defines a projection class: the getters, and the public fields, will be used to restrict which fields should be
* retrieved from the database.
*
* @return a new query with the same state as the previous one (params, page, range, lockMode, hints, ...).
*/
fun <NewEntity: Any> project(type: Class<NewEntity>): PanacheQuery<NewEntity>
fun <NewEntity : Any> project(type: Class<NewEntity>): PanacheQuery<NewEntity>

/**
* Sets the current page.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ package io.quarkus.hibernate.orm.panache.kotlin
*
* @param Entity The type of entity to operate on
*/
interface PanacheRepository<Entity : Any>: PanacheRepositoryBase<Entity, Long>
interface PanacheRepository<Entity : Any> : PanacheRepositoryBase<Entity, Long>
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import kotlin.reflect.KClass
* @param Entity The type of entity to operate on
* @param Id The ID type of the entity
*/
interface PanacheRepositoryBase<Entity : Any, Id: Any> {
interface PanacheRepositoryBase<Entity : Any, Id : Any> {

/**
* Returns the [EntityManager] for the [Entity] for extra operations (eg. CriteriaQueries)
Expand All @@ -33,8 +33,10 @@ interface PanacheRepositoryBase<Entity : Any, Id: Any> {
* @return the [EntityManager] tied to the given class
*/
@GenerateBridge
@Deprecated(message="use Panache.getEntityManager() instead to access an entity manager for any entity class",
replaceWith = ReplaceWith("Panache.getEntityManager()"))
@Deprecated(
message = "use Panache.getEntityManager() instead to access an entity manager for any entity class",
replaceWith = ReplaceWith("Panache.getEntityManager()")
)
fun getEntityManager(clazz: KClass<Any>): EntityManager = throw implementationInjectionMissing()

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import java.util.stream.Stream
import javax.persistence.EntityManager
import javax.persistence.LockModeType

class PanacheQueryImpl<Entity: Any> : PanacheQuery<Entity> {
class PanacheQueryImpl<Entity : Any> : PanacheQuery<Entity> {
private var delegate: CommonPanacheQueryImpl<Entity>

internal constructor(em: EntityManager?, query: String?, orderBy: String?, paramsArrayOrMap: Any?) {
Expand All @@ -20,7 +20,7 @@ class PanacheQueryImpl<Entity: Any> : PanacheQuery<Entity> {
}

// Builder
override fun <NewEntity: Any> project(type: Class<NewEntity>): PanacheQuery<NewEntity> {
override fun <NewEntity : Any> project(type: Class<NewEntity>): PanacheQuery<NewEntity> {
return PanacheQueryImpl(delegate.project(type))
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.quarkus.hibernate.orm.panache.kotlin.runtime


import io.quarkus.gizmo.Gizmo
import io.quarkus.hibernate.orm.panache.kotlin.PanacheCompanionBase
import io.quarkus.hibernate.orm.panache.kotlin.PanacheEntityBase
Expand Down Expand Up @@ -41,24 +40,26 @@ class TestAnalogs {
fun testPanacheEntityBase() {
val javaMethods = map(JavaPanacheEntityBase::class).methods
val kotlinMethods = map(PanacheEntityBase::class).methods
val companionMethods = map(PanacheCompanionBase::class,
ByteCodeType(PanacheEntityBase::class.java)).methods
val companionMethods = map(
PanacheCompanionBase::class,
ByteCodeType(PanacheEntityBase::class.java)
).methods
val implemented = mutableListOf<Method>()

javaMethods
.forEach {
if (!it.isStatic()) {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
} else {
if (it in companionMethods) {
companionMethods -= it
implemented += it
}
.forEach {
if (!it.isStatic()) {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
} else {
if (it in companionMethods) {
companionMethods -= it
implemented += it
}
}
}
javaMethods.removeIf {
it.name.endsWith("Optional") || it in implemented
}
Expand All @@ -78,22 +79,21 @@ class TestAnalogs {
}
}


private fun KClass<*>.bytes() =
java.classLoader.getResourceAsStream(qualifiedName.toString().replace(".", "/") + ".class")
java.classLoader.getResourceAsStream(qualifiedName.toString().replace(".", "/") + ".class")

private fun compare(javaClass: AnalogVisitor, kotlinClass: AnalogVisitor, allowList: List<String> = listOf()) {
val javaMethods = javaClass.methods
val kotlinMethods = kotlinClass.methods
val implemented = mutableListOf<Method>()

javaMethods
.forEach {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
.forEach {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
}

javaMethods.removeIf {
it.name.endsWith("Optional") ||
Expand All @@ -112,29 +112,34 @@ class TestAnalogs {
private fun methods(label: String, methods: List<Method>) {
println("$label: ")
methods.toSortedSet(compareBy { it.toString() })
.forEach {
println(it)
}
.forEach {
println(it)
}
}
}

private fun <E> List<E>.byLine(): String {
val map = map { it.toString() }
return map
.joinToString("\n" )
.joinToString("\n")
}

class AnalogVisitor(val erasedType: ByteCodeType? = null) : ClassVisitor(Gizmo.ASM_API_VERSION) {
val methods = mutableListOf<Method>()
override fun visitMethod(access: Int, name: String, descriptor: String, signature: String?,
exceptions: Array<out String>?): MethodVisitor? {
override fun visitMethod(
access: Int,
name: String,
descriptor: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
if (name != "<init>") {
val type = descriptor.substringAfterLast(")").trim()
var parameters = descriptor.substring(
descriptor.indexOf("("),
descriptor.lastIndexOf(")") + 1
)
erasedType?.let { type->
erasedType?.let { type ->
parameters = parameters.replace(type.descriptor(), OBJECT.descriptor())
}

Expand All @@ -149,7 +154,7 @@ class Method(val access: Int, val name: String, val type: String, val parameters

override fun toString(): String {
return (if (isStatic()) "static " else "") + "fun ${name}$parameters" +
(if (type.isNotBlank()) ": $type" else "") //+
(if (type.isNotBlank()) ": $type" else "") // +
}

override fun equals(other: Any?): Boolean {
Expand All @@ -168,7 +173,6 @@ class Method(val access: Int, val name: String, val type: String, val parameters
result = 31 * result + parameters.hashCode()
return result
}

}

fun Int.matches(mask: Int) = (this and mask) == mask
Expand Down
Loading