Skip to content

Commit

Permalink
Get the plugin working again and fix some issues
Browse files Browse the repository at this point in the history
  • Loading branch information
bparent-atl committed Nov 5, 2023
1 parent 10b63e2 commit 05b193e
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 71 deletions.
1 change: 1 addition & 0 deletions mr-clean-debug-processor/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ plugins {

dependencies {
implementation(project(":mr-clean-processor-core"))
implementation(project(":mr-clean-runtime"))
ksp(libs.autoservice.ksp)
implementation(libs.autoservice.annotations)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ class MrCleanDebugProcessor(
private val logger: KSPLogger,
) : SymbolProcessor {
override fun process(resolver: Resolver): List<KSAnnotated> {
logger.warn("Mr. Clean Debug Processor has $options")
logger.info("Mr. Clean Debug Processor has $options")
val debugOptions = mutableMapOf<String, String>()
debugOptions.putAll(options)
if (options[MrCleanCoreProcessor.DEBUG_KEY] == null) {
logger.warn("\"MrCleanCoreProcessor.DEBUG_KEY\" not set, defatuling to true")
logger.info("\"MrCleanCoreProcessor.DEBUG_KEY\" not set, defatuling to true")
debugOptions[MrCleanCoreProcessor.DEBUG_KEY] = "true"
}
if (options[MrCleanCoreProcessor.ROOT_GENERATOR_KEY] == null) {
logger.warn("\"$MrCleanCoreProcessor.ROOT_GENERATOR_KEY\" not set, defaulting to true")
logger.info("\"$MrCleanCoreProcessor.ROOT_GENERATOR_KEY\" not set, defaulting to true")
debugOptions[MrCleanCoreProcessor.ROOT_GENERATOR_KEY] = "true"
}
return MrCleanCoreProcessor(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
package com.trello.mrclean.plugin

import org.gradle.api.DefaultTask
import org.gradle.api.provider.Property
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import java.io.File

abstract class GenerateRootFunctions : DefaultTask() {
@get:OutputDirectory
abstract val outputDir: DirectoryProperty
@get:OutputDirectory
abstract val outputDir: DirectoryProperty

@get:Input
abstract val packageName: Property<String>
@get:Input
abstract val packageName: Property<String>

@Suppress("unused") // Invoked by Gradle.
@TaskAction
fun brewJava() {
brewJava(outputDir.asFile.get(), packageName.get())
}
@Suppress("unused") // Invoked by Gradle.
@TaskAction
fun brewJava() {
brewJava(outputDir.asFile.get(), packageName.get())
}
}

fun brewJava(outputDir: File, packageName: String) {
val compiler = RootFunctionGenerator()
compiler.createRootFunction(packageName).writeTo(outputDir)
}
val compiler = RootFunctionGenerator()
compiler.createRootFunction(packageName).writeTo(outputDir)
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import com.android.builder.errors.EvalIssueException
import com.android.builder.errors.IssueReporter
import com.google.devtools.ksp.gradle.KspExtension
import com.trello.mrclean.VERSION
import com.trello.mrclean.annotations.Sanitize
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionContainer
Expand All @@ -20,49 +19,38 @@ import kotlin.reflect.KClass
* Based on butterknife's multi-module gradle plugin
*/
class MrCleanPlugin : Plugin<Project> {
private val sanitize = Sanitize::class.java
private val log by lazy {
LoggerFactory.getLogger("Mr. Clean")
}

override fun apply(project: Project) {
project.plugins.apply("com.google.devtools.ksp")
log.warn("MrClean: attmpeing to query extension")
// val hasKsp = project.extensions.findByName("ksp") != null
val kspExtension = getOrCreateKsp(project, "ksp")
// val kspExtension = if (hasKsp) {
// log.warn("MrClean: found ksp")
// project.extensions.getByName("ksp") as KspExtension
// project.extensions.getByType(KspExtension::class.java)
// } else {
// log.warn("MrClean: trying to create ksp")
// project.extensions.create("ksp", KspExtension::class.java)
// }
kspExtension.arg("mrclean.debug", "false")
log.warn("MrClean: got ksp extension of $kspExtension")
addKspDeps(project)
// project.extensions.
val baseExtension = project.extensions.getByType(BaseExtension::class.java)
val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java)
val buildTypeSet = mutableSetOf<String>()
// we are generating the root here, so we don't need to generate it in the processor
kspExtension.arg("mrclean.rootgenerator", "false")
androidComponents.onVariants { variant ->
val buildType = variant.buildType
if (buildType != null && !buildTypeSet.contains(buildType)) {
val isDebug = (variant.buildType == "debug")
val cleaned = buildType.replaceFirstChar { it.uppercaseChar() }
addMrCleanProcessor(project, cleaned, isDebug)
buildTypeSet.add(buildType)
}
val packageName = getPackageNameBase(baseExtension)
kspExtension.arg("mrclean.packagename", packageName)
val isDebug = (variant.buildType == "debug")
if (isDebug) {
log.warn("attempting to add debug ksp")
val debugKsp = getOrCreateKsp(project, "kspDebug")
debugKsp.arg("mrclean.debug", isDebug.toString())
}
// log.warn("is debug? ${variant.buildType} ${(variant.buildType == "debug")}")
// kspExtension.arg("mrclean.debug", (variant.buildType == "debug").toString())
val taskName = "generate${variant.name.capitalize()}RootSanitizeFunction"
val outputDir = project.buildDir.resolve("generated/source/mrclean/${variant.name}")
log.debug("MrClean: task $taskName using directory $outputDir")
log.info("MrClean: task $taskName using directory $outputDir")
val task = project.tasks.register(taskName, GenerateRootFunctions::class.java) {
it.outputDir.set(outputDir)
it.packageName.set(packageName)
}
variant.sources.assets?.addGeneratedSourceDirectory(
log.info("MrClean: setting ${variant.sources.java} to ${GenerateRootFunctions::outputDir}")
variant.sources.java?.addGeneratedSourceDirectory(
task,
GenerateRootFunctions::outputDir,
)
Expand All @@ -72,32 +60,34 @@ class MrCleanPlugin : Plugin<Project> {
private fun getOrCreateKsp(project: Project, name: String): KspExtension {
val hasKsp = project.extensions.findByName(name) != null
return if (hasKsp) {
log.warn("MrClean: found $name")
log.info("MrClean: found $name")
project.extensions.getByName(name) as KspExtension
// project.extensions.getByType(KspExtension::class.java)
} else {
log.warn("MrClean: trying to create $name")
log.info("MrClean: trying to create $name")
project.extensions.create(name, KspExtension::class.java)
}
}

private fun addKspDeps(project: Project) {
val implDeps = project.configurations.getByName("implementation").dependencies
implDeps.add(project.dependencies.create("com.trello.mrclean:mr-clean-annotations:$VERSION"))
// val kaptDeps = project.configurations.getByName("kapt").dependencies
// kaptDeps.add(project.dependencies.create("com.trello.mrclean:mr-clean-processor:$VERSION"))
// println("this is new")
// log.error("really new ${sanitize.canonicalName}")
// log.error("really new ${Sanitize::class.qualifiedName}")
val kspDeps = project.configurations.getByName("ksp").dependencies
kspDeps.add(project.dependencies.create("com.trello.mrclean:mr-clean-processor:$VERSION"))
val kspDeps2 = project.configurations.getByName("kspDebug").dependencies
kspDeps2.add(project.dependencies.create("com.trello.mrclean:mr-clean-debug-processor:$VERSION"))
implDeps.add(project.dependencies.create("com.trello.mrclean:mr-clean-runtime:$VERSION"))
}

private fun addMrCleanProcessor(project: Project, configuration: String, isDebug: Boolean) {
val coordinates = if (isDebug) {
"com.trello.mrclean:mr-clean-debug-processor"
} else {
"com.trello.mrclean:mr-clean-processor"
}
log.info("Mr Clean is adding: ksp$configuration $coordinates:$VERSION")
val kspDep = project.configurations.getByName("ksp$configuration").dependencies
kspDep.add(project.dependencies.create("$coordinates:$VERSION"))
}

private fun getPackageNameBase(extension: BaseExtension): String {
return if (extension.namespace != null) {
log.debug("using namespace ${extension.namespace}")
log.info("using namespace ${extension.namespace}")
extension.namespace!!
} else {
log.debug("couldn't find a namespace")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,33 +17,33 @@ class MrCleanCoreProcessor(
private val logger: KSPLogger,
) {
fun process(resolver: Resolver): List<KSAnnotated> {
logger.warn("Mr. Clean Core Processor has $options")
logger.info("Mr. Clean Core Processor has $options")

val packageName = options[PACKAGE_KEY]

if (packageName == null) {
logger.error("Mr. Clean didn't get a value for package name, a package must be passed in with the key \"mrclean.packagename\"")
return emptyList()
}

val symbols = resolver
.getSymbolsWithAnnotation(Sanitize::class.qualifiedName!!)
.filterIsInstance<KSClassDeclaration>()
val annotationName = Sanitize::class.qualifiedName!!
val unfilteredSymbols = resolver.getSymbolsWithAnnotation(annotationName)
val symbolsNotProcessed = unfilteredSymbols.filterNot { it.validate(symbolPredicate) }.toList()
val symbols = unfilteredSymbols.filterIsInstance<KSClassDeclaration>().filter { it.validate(symbolPredicate) }

if (!symbols.iterator().hasNext()) {
logger.warn("Mr. Clean found no symbols to process, exiting")
return emptyList()
logger.info("Mr. Clean found no symbols to process, exiting")
return symbolsNotProcessed
}

val rootFromOpts = options[ROOT_GENERATOR_KEY]
val debugFromOpts = options[DEBUG_KEY]

if (rootFromOpts == null) {
logger.warn("Mr. Clean defaulting to not generating a root function. Can overrider with \"$ROOT_GENERATOR_KEY\"")
logger.info("Mr. Clean defaulting to not generating a root function. Can overrider with \"$ROOT_GENERATOR_KEY\"")
}

if (debugFromOpts == null) {
logger.warn("Mr. Clean defaulting to sanitization. Can be overriden with \"$DEBUG_KEY\"")
logger.info("Mr. Clean defaulting to sanitization. Can be overriden with \"$DEBUG_KEY\"")
}

val isDebug = debugFromOpts?.toBoolean() ?: false
Expand Down Expand Up @@ -96,14 +96,31 @@ class MrCleanCoreProcessor(
)
}
if (generateRoot) {
logger.warn("Mr. Clean generating root function Any.santizedToString()")
logger.info("Mr. Clean generating root function Any.santizedToString()")
createRootFunction(packageName).writeTo(codeGenerator, false)
}
val toList = symbols.filterNot { it.validate() }.toList()
logger.warn("Mr. Clean processed $symbolCount symbols returning ${toList.size}")
return toList
logger.info("Mr. Clean processed $symbolCount symbols returning ${symbolsNotProcessed.size}")
return symbolsNotProcessed
}

private val symbolPredicate: (data: KSNode?, declaration: KSNode) -> Boolean =
{ data, declaration ->
when (declaration) {
// we only care about class, annotation and property
is KSClassDeclaration,
is KSAnnotation,
is KSPropertyDeclaration,
-> {
true
}
// only care about types that belong to parameters
is KSTypeReference -> data is KSPropertyDeclaration
else -> {
false
}
}
}

private fun createRootFunction(packageName: String): FileSpec {
val rootFunction = FunSpec.builder("sanitizedToString")
.addModifiers(KModifier.INTERNAL)
Expand All @@ -126,5 +143,3 @@ class MrCleanCoreProcessor(
const val PACKAGE_KEY = "mrclean.packagename"
}
}


Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ data class MrCleanClassData(
val properties: List<MrCleanProperty>,
val originatingFile: KSFile?,
) {
fun getFileName() = "SanitizationFor$enclosingPackage$simpleName"
fun getFileName() = "SanitizationFor$enclosingPackage${qualifiedName.removePrefix(qualifiedPackage)}"
}

data class MrCleanProperty(
Expand Down
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ include ':mr-clean-runtime'
include ':mr-clean-processor'
include ':mr-clean-processor-core'
include ':mr-clean-debug-processor'
//include ':mr-clean-plugin'
include ':mr-clean-plugin'

0 comments on commit 05b193e

Please sign in to comment.