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

sortDependencies task #165

Merged
merged 4 commits into from
Sep 21, 2020
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
11 changes: 11 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

@file:Suppress("MagicNumber")

import formatting.sortDependencies
import io.gitlab.arturbosch.detekt.*
import kotlinx.knit.*
import kotlinx.validation.*
Expand Down Expand Up @@ -333,6 +334,16 @@ val generateDependencyGraph by tasks.registering {
}
}

val sortDependencies by tasks.registering {

description = "sort all dependencies in a gradle kts file"
group = "refactor"

doLast {
sortDependencies()
}
}

subprojects {

// force update all transitive dependencies (prevents some library leaking an old version)
Expand Down
14 changes: 10 additions & 4 deletions buildSrc/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,25 @@
* limitations under the License.
*/

repositories {
jcenter()
}

plugins {
`kotlin-dsl`
}

repositories {
google()
jcenter()
maven("https://oss.sonatype.org/content/repositories/snapshots")
}

kotlinDslPluginOptions {
experimentalWarning.set(false)
}

dependencies {

compileOnly(gradleApi())

implementation("org.jetbrains.kotlin:kotlin-compiler-embeddable:1.4.10") // update Dependencies.kt as well
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.10") // update Dependencies.kt as well
implementation("com.android.tools.build:gradle:4.0.0") // update Dependencies.kt as well
}
119 changes: 119 additions & 0 deletions buildSrc/src/main/kotlin/formatting/dependencies.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* Copyright (C) 2020 Rick Busarow
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package formatting


import formatting.GradleDependencyVisitor.Properties
import org.gradle.api.Project
import org.jetbrains.kotlin.psi.*
import util.psi.asKtFile
import util.psi.visitor.KotlinVisitor
import java.io.File
import kotlin.properties.Delegates
import kotlin.system.measureTimeMillis

fun Project.sortDependencies() {

val totalParseTime = measureTimeMillis {

subprojects.forEach {

val maybeGradleFile = File("${it.projectDir}/build.gradle.kts")

if (maybeGradleFile.exists()) {

val gradle = maybeGradleFile.asKtFile()

val props = GradleDependencyVisitor().parse(gradle)

val old = props.oldDependencies ?: "---------------"
val new = props.newDependencies ?: "---------------"

val newText = gradle.text.replace(old, new)

maybeGradleFile.writeText(newText)
}
}
}

println("total parsing time: $totalParseTime ms")

}

class GradleDependencyVisitor : KotlinVisitor<Properties>() {

class Properties {
var root: KtFile by Delegates.notNull()
var oldDependencies: String? = null
var newDependencies: String? = null
}

override val properties = Properties()

override fun visitKtFile(file: KtFile) {
properties.root = file

super.visitKtFile(file)
}

override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)

if (expression.text.startsWith("dependencies {")) {

val declarations = expression.children
.mapNotNull { it as? KtLambdaArgument }
.map { lambdaArg ->
lambdaArg.children.mapNotNull { it as? KtLambdaExpression }
.map { lambdaExpression ->
lambdaExpression.children.mapNotNull { it as? KtExpression }
.map { ktExpression ->
ktExpression.children.mapNotNull { declarationExpression ->
properties.oldDependencies = declarationExpression.text
declarationExpression as? KtExpression
}
.map { declarationExpression ->
declarationExpression.children.mapNotNull { it as? KtCallExpression }
.map { it.text }
}
}
}
}
.flatten()
.flatten()
.flatten()
.flatten()
.groupBy { it.split("[(.]".toRegex()).take(2).joinToString("-") }

val comparator = compareBy<String>({ it.startsWith("kapt") }, { it })

val sortedKeys = declarations.keys.sortedWith(comparator)

val newDeps = sortedKeys.joinToString("\n\n") { key ->

declarations.getValue(key)
.toSet()
.sortedBy {
@Suppress("DefaultLocale")
it.toLowerCase()
}
.joinToString("\n") { " $it" }
}.trim()

properties.newDependencies = newDeps
}
}
}
46 changes: 46 additions & 0 deletions buildSrc/src/main/kotlin/util/psi/ktFile.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
@file:Suppress("TooManyFunctions")

package util.psi

import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import java.io.File
import java.io.FileNotFoundException

val RELATIVE_PATH: Key<String> = Key("relativePath")
val ABSOLUTE_PATH: Key<String> = Key("absolutePath")

fun File.asKtFile(): KtFile =
(psiFileFactory.createFileFromText(name, KotlinLanguage.INSTANCE, readText()) as? KtFile)?.apply {
putUserData(ABSOLUTE_PATH, [email protected])
} ?: throw FileNotFoundException("could not find file $this")

fun KtFile.asFile(): File = File(absolutePath())

fun KtFile.absolutePath(): String =
getUserData(ABSOLUTE_PATH) ?: error("KtFile '$name' expected to have an absolute path.")

fun KtFile.relativePath(): String = getUserData(RELATIVE_PATH)
?: error("KtFile '$name' expected to have an relative path.")

fun KtFile.replaceClass(oldClass: KtClass, newClass: KtClass): KtFile {

val newText = text.replace(oldClass.text, newClass.text)

val path = absolutePath()

return (psiFileFactory.createFileFromText(name, KotlinLanguage.INSTANCE, newText) as KtFile).apply {
putUserData(ABSOLUTE_PATH, path)
}
}

fun KtFile.write(path: String = absolutePath()) {

val javaFile = File(path)

javaFile.mkdirs()
javaFile.writeText(text)
}
34 changes: 34 additions & 0 deletions buildSrc/src/main/kotlin/util/psi/psi.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package util.psi

import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer
import org.jetbrains.kotlin.com.intellij.psi.PsiFileFactory
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.psi.KtPsiFactory
import sun.java2d.*

val configuration = CompilerConfiguration().apply {
put(
CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY,
PrintingMessageCollector(
System.err,
MessageRenderer.PLAIN_FULL_PATHS,
false
)
)
}

private val psiProject by lazy {
KotlinCoreEnvironment.createForProduction(
Disposer.newDisposable(),
configuration,
EnvironmentConfigFiles.JVM_CONFIG_FILES
).project
}

val psiFileFactory: PsiFileFactory = PsiFileFactory.getInstance(psiProject)
val psiElementFactory = KtPsiFactory(psiProject, false)
19 changes: 19 additions & 0 deletions buildSrc/src/main/kotlin/util/psi/visitor/KotlinVisitor.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package util.psi.visitor

import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import kotlin.properties.Delegates

abstract class KotlinVisitor<T> : KtTreeVisitorVoid() {

protected var root: KtFile by Delegates.notNull()
private set

abstract val properties: T

fun parse(file: KtFile): T {
root = file
file.accept(this)
return properties
}
}
7 changes: 3 additions & 4 deletions dispatch-android-espresso/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,19 @@ android {

dependencies {

implementation(Libs.AndroidX.Test.Espresso.core)
implementation(Libs.AndroidX.Test.runner)
implementation(Libs.Kotlin.stdlib)

implementation(Libs.Kotlinx.Coroutines.android)
implementation(Libs.Kotlinx.Coroutines.core)

implementation(project(":dispatch-core"))

implementation(Libs.AndroidX.Test.runner)
implementation(Libs.AndroidX.Test.Espresso.core)

testImplementation(Libs.JUnit.jUnit4)
testImplementation(Libs.Kotest.assertions)
testImplementation(Libs.Kotest.runner)
testImplementation(Libs.MockK.core)
testImplementation(Libs.Robolectric.core)

testImplementation(project(":dispatch-internal-test"))
}
16 changes: 6 additions & 10 deletions dispatch-android-espresso/samples/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -39,31 +39,27 @@ android {
}

dependencies {
implementation(Libs.Kotlin.stdlib)

implementation(Libs.Kotlin.stdlib)
implementation(Libs.Kotlinx.Coroutines.core)

implementation(project(":dispatch-core"))
implementation(project(":dispatch-android-espresso"))
implementation(project(":dispatch-android-lifecycle"))
implementation(project(":dispatch-android-lifecycle-extensions"))
implementation(project(":dispatch-android-viewmodel"))
implementation(project(":dispatch-core"))

testImplementation(project(":dispatch-internal-test"))

testImplementation(Libs.AndroidX.Test.Espresso.core)
testImplementation(Libs.AndroidX.Test.runner)
testImplementation(Libs.JUnit.jUnit4)
testImplementation(Libs.Kotest.assertions)
testImplementation(Libs.Kotest.properties)
testImplementation(Libs.Kotest.runner)

testImplementation(Libs.AndroidX.Test.runner)
testImplementation(Libs.AndroidX.Test.Espresso.core)

testImplementation(Libs.Kotlin.test)
testImplementation(Libs.Kotlin.testCommon)

testImplementation(Libs.Kotlinx.Coroutines.test)
testImplementation(Libs.Robolectric.core)

testImplementation(Libs.Kotlinx.Coroutines.test)
testImplementation(project(":dispatch-internal-test"))

}
27 changes: 12 additions & 15 deletions dispatch-android-lifecycle-extensions/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -45,32 +45,29 @@ android {

dependencies {

api(project(":dispatch-android-lifecycle"))
api(project(":dispatch-core"))

implementation(Libs.AndroidX.Fragment.core)
implementation(Libs.AndroidX.Lifecycle.common)
testImplementation(Libs.AndroidX.Lifecycle.runtime)

implementation(Libs.Kotlin.stdlib)

implementation(Libs.Kotlinx.Coroutines.android)
implementation(Libs.Kotlinx.Coroutines.core)

api(project(":dispatch-android-lifecycle"))
api(project(":dispatch-core"))
testImplementation(project(":dispatch-test-junit4"))
testImplementation(project(":dispatch-test-junit5"))
testImplementation(project(":dispatch-internal-test"))
testImplementation(project(":dispatch-internal-test-android"))

testImplementation(Libs.AndroidX.Lifecycle.runtime)
testImplementation(Libs.AndroidX.Test.Arch.core)
testImplementation(Libs.AndroidX.Test.Espresso.core)
testImplementation(Libs.AndroidX.Test.runner)
testImplementation(Libs.JUnit.jUnit5)
testImplementation(Libs.Kotest.assertions)
testImplementation(Libs.Kotest.properties)
testImplementation(Libs.Kotest.runner)
testImplementation(Libs.Kotlinx.Coroutines.test)

testImplementation(Libs.AndroidX.Test.runner)
testImplementation(Libs.AndroidX.Test.Espresso.core)
testImplementation(Libs.AndroidX.Test.Arch.core)
testImplementation(Libs.RickBusarow.Hermit.junit5)
testImplementation(Libs.Robolectric.core)

testImplementation(Libs.RickBusarow.Hermit.junit5)
testImplementation(project(":dispatch-internal-test"))
testImplementation(project(":dispatch-internal-test-android"))
testImplementation(project(":dispatch-test-junit4"))
testImplementation(project(":dispatch-test-junit5"))
}
Loading