-
Notifications
You must be signed in to change notification settings - Fork 268
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 command line parser and entry points #1885
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
plugins { | ||
kotlin("jvm") | ||
} | ||
|
||
dependencies { | ||
implementation(kotlin("stdlib")) | ||
implementation(project(":api")) | ||
} |
132 changes: 132 additions & 0 deletions
132
cmdline-parser-gen/src/main/kotlin/CmdlineParserGenerator.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
import com.google.devtools.ksp.processing.* | ||
import com.google.devtools.ksp.symbol.* | ||
import java.io.OutputStream | ||
|
||
private fun OutputStream.appendText(str: String) { | ||
this.write(str.toByteArray()) | ||
} | ||
|
||
private fun OutputStream.appendLine(str: String = "") { | ||
appendText(str + System.lineSeparator()) | ||
} | ||
|
||
// modueName => -module-name | ||
private fun String.camelToOptionName(): String = fold(StringBuilder()) { acc, c -> | ||
acc.let { | ||
val lower = c.lowercase() | ||
acc.append(if (acc.isEmpty() || c.isUpperCase()) "-$lower" else lower) | ||
} | ||
}.toString() | ||
|
||
class CmdlineParserGenerator( | ||
val codeGenerator: CodeGenerator, | ||
val logger: KSPLogger, | ||
val options: Map<String, String> | ||
) : SymbolProcessor { | ||
override fun process(resolver: Resolver): List<KSAnnotated> { | ||
val annotationName = "com.google.devtools.ksp.processing.KSPArgParserGen" | ||
val kspConfigBuilders = | ||
resolver.getSymbolsWithAnnotation(annotationName) | ||
|
||
kspConfigBuilders.filterIsInstance<KSClassDeclaration>().forEach { builderClass -> | ||
val parserName = builderClass.annotations.single { | ||
it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationName | ||
}.arguments.single().value as String | ||
val configClass = builderClass.parentDeclaration as KSClassDeclaration | ||
val builderName = "${configClass.simpleName.asString()}.${builderClass.simpleName.asString()}" | ||
codeGenerator.createNewFile( | ||
Dependencies(false, builderClass.containingFile!!), | ||
builderClass.packageName.asString(), | ||
parserName | ||
).use { os -> | ||
os.appendLine("package ${builderClass.packageName.asString()}") | ||
os.appendLine() | ||
os.appendLine( | ||
"fun $parserName(args: Array<String>): Pair<${configClass.simpleName.asString()}, List<String>> {" | ||
) | ||
os.appendLine(" val processorClasspath = mutableListOf<String>()") | ||
os.appendLine(" return Pair($builderName().apply {") | ||
os.appendLine(" var i = 0") | ||
os.appendLine(" while (i < args.size) {") | ||
os.appendLine(" val arg = args[i++]") | ||
os.appendLine(" when {") | ||
|
||
builderClass.getAllProperties().filter { it.setter != null }.forEach { prop -> | ||
val type = prop.type.resolve() | ||
val typeName = type.declaration.simpleName.asString() | ||
val propName = prop.simpleName.asString() | ||
val optionName = propName.camelToOptionName() | ||
val optionNameLen = optionName.length | ||
when (typeName) { | ||
"String", "Boolean", "File" -> { | ||
os.appendLine( | ||
" arg == \"$optionName\" -> " + | ||
"$propName = parse$typeName(getArg(args, i++))" | ||
) | ||
os.appendLine( | ||
" arg.startsWith(\"$optionName=\") -> " + | ||
"$propName = parse$typeName(arg.substring(${optionNameLen + 1}))" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. substringAfter? |
||
) | ||
} | ||
"List", "Map" -> { | ||
val elementTypeName = | ||
type.arguments.last().type!!.resolve().declaration.simpleName.asString() | ||
os.appendLine( | ||
" arg == \"$optionName\" -> " + | ||
"$propName = parse$typeName(getArg(args, i++), ::parse$elementTypeName)" | ||
) | ||
os.appendLine( | ||
" arg.startsWith(\"$optionName=\") -> " + | ||
"$propName = parse$typeName(arg.substring(${optionNameLen + 1}), " + | ||
"::parse$elementTypeName)" | ||
) | ||
} | ||
else -> { | ||
throw IllegalArgumentException("Unknown type of option `$propName: ${prop.type}`") | ||
} | ||
} | ||
} | ||
|
||
// Free args are processor classpath | ||
os.appendLine(" else -> {") | ||
os.appendLine(" processorClasspath.addAll(parseList(arg, ::parseString))") | ||
os.appendLine(" }") | ||
os.appendLine(" }") | ||
os.appendLine(" }") | ||
os.appendLine(" }.build(), processorClasspath)") | ||
os.appendLine("}") | ||
} | ||
|
||
codeGenerator.createNewFile( | ||
Dependencies(false, builderClass.containingFile!!), | ||
builderClass.packageName.asString(), | ||
parserName + "Help" | ||
).use { os -> | ||
os.appendLine("package ${builderClass.packageName.asString()}") | ||
os.appendLine() | ||
os.appendLine( | ||
"fun ${parserName}Help(): String = \"\"\"" | ||
) | ||
builderClass.getAllProperties().filter { it.setter != null }.forEach { prop -> | ||
val type = prop.type.resolve() | ||
val typeName = type.toString() | ||
val propName = prop.simpleName.asString() | ||
val optionName = propName.camelToOptionName() | ||
val prefix = if (Modifier.LATEINIT in prop.modifiers) "*" else " " | ||
os.appendLine("$prefix $optionName=$typeName") | ||
} | ||
os.appendLine("* <processor classpath>") | ||
os.appendLine("\"\"\"") | ||
} | ||
} | ||
return emptyList() | ||
} | ||
} | ||
|
||
class CmdlineParserGeneratorProvider : SymbolProcessorProvider { | ||
override fun create( | ||
environment: SymbolProcessorEnvironment | ||
): SymbolProcessor { | ||
return CmdlineParserGenerator(environment.codeGenerator, environment.logger, environment.options) | ||
} | ||
} |
1 change: 1 addition & 0 deletions
1
...in/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
CmdlineParserGeneratorProvider |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
51 changes: 51 additions & 0 deletions
51
common-deps/src/test/kotlin/com/google/devtools/ksp/CommandLineArgParserTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package com.google.devtools.ksp | ||
|
||
import com.google.devtools.ksp.processing.kspJvmArgParser | ||
import com.google.devtools.ksp.processing.kspJvmArgParserHelp | ||
import org.junit.Assert | ||
import org.junit.Test | ||
import java.io.File | ||
|
||
class CommandLineArgParserTest { | ||
@Test | ||
fun testJvm() { | ||
val args = arrayListOf<String>( | ||
"-module-name=MyModule", | ||
"-source-roots", "/path/to/A:/path/to/B", | ||
"/path/to/processorA.jar", | ||
"-kotlin-output-dir=/path/to/output/kotlin", | ||
"-java-output-dir=/path/to/output/java", | ||
"-class-output-dir=/path/to/output/class", | ||
"-resource-output-dir=/path/to/output/resource", | ||
"-language-version=2.0", | ||
"-api-version=2.0", | ||
"-jvm-target", "21", | ||
"-project-base-dir", "/path/to/base", | ||
"-output-base-dir", "/path/to/output", | ||
"-caches-dir", "/path/to/caches", | ||
"/path/to/processorB.jar:rel/to/processorC.jar", | ||
).toTypedArray() | ||
val (config, classpath) = kspJvmArgParser(args) | ||
Assert.assertEquals( | ||
listOf("/path/to/A", "/path/to/B").map(::File), | ||
config.sourceRoots | ||
) | ||
Assert.assertEquals( | ||
"MyModule", | ||
config.moduleName | ||
) | ||
Assert.assertEquals( | ||
listOf("/path/to/processorA.jar", "/path/to/processorB.jar", "rel/to/processorC.jar"), | ||
classpath | ||
) | ||
} | ||
|
||
@Test | ||
fun testJvmHelp() { | ||
val helpMsg = kspJvmArgParserHelp() | ||
Assert.assertTrue("* -java-output-dir=File" in helpMsg) | ||
Assert.assertTrue(" -libraries=List<File>" in helpMsg) | ||
Assert.assertTrue("* <processor classpath>" in helpMsg) | ||
println(helpMsg) | ||
} | ||
} |
17 changes: 17 additions & 0 deletions
17
kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/cmdline/KSPCommonMain.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package com.google.devtools.ksp.cmdline | ||
|
||
import com.google.devtools.ksp.processing.kspCommonArgParser | ||
import com.google.devtools.ksp.processing.kspCommonArgParserHelp | ||
|
||
class KSPCommonMain { | ||
companion object { | ||
@JvmStatic | ||
fun main(args: Array<String>) { | ||
if ("-h" in args || "--help" in args) { | ||
printHelpMsg(kspCommonArgParserHelp()) | ||
} else { | ||
runWithArgs(args, ::kspCommonArgParser) | ||
} | ||
} | ||
} | ||
} |
17 changes: 17 additions & 0 deletions
17
kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/cmdline/KSPJsMain.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package com.google.devtools.ksp.cmdline | ||
|
||
import com.google.devtools.ksp.processing.kspJsArgParser | ||
import com.google.devtools.ksp.processing.kspJsArgParserHelp | ||
|
||
class KSPJsMain { | ||
companion object { | ||
@JvmStatic | ||
fun main(args: Array<String>) { | ||
if ("-h" in args || "--help" in args) { | ||
printHelpMsg(kspJsArgParserHelp()) | ||
} else { | ||
runWithArgs(args, ::kspJsArgParser) | ||
} | ||
} | ||
} | ||
} |
46 changes: 46 additions & 0 deletions
46
kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/cmdline/KSPJvmMain.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package com.google.devtools.ksp.cmdline | ||
|
||
import com.google.devtools.ksp.impl.KotlinSymbolProcessing | ||
import com.google.devtools.ksp.processing.KSPConfig | ||
import com.google.devtools.ksp.processing.KspGradleLogger | ||
import com.google.devtools.ksp.processing.SymbolProcessorProvider | ||
import com.google.devtools.ksp.processing.kspJvmArgParser | ||
import com.google.devtools.ksp.processing.kspJvmArgParserHelp | ||
import java.io.File | ||
import java.net.URLClassLoader | ||
import java.util.ServiceLoader | ||
|
||
class KSPJvmMain { | ||
companion object { | ||
@JvmStatic | ||
fun main(args: Array<String>) { | ||
if ("-h" in args || "--help" in args) { | ||
printHelpMsg(kspJvmArgParserHelp()) | ||
} else { | ||
runWithArgs(args, ::kspJvmArgParser) | ||
} | ||
} | ||
} | ||
} | ||
|
||
internal fun printHelpMsg(optionsList: String) { | ||
println("Available options:") | ||
println(optionsList) | ||
println("where:") | ||
println(" * is required") | ||
println(" List is colon separated. E.g., arg1:arg2:arg3") | ||
println(" Map is in the form key1=value1:key2=value2") | ||
} | ||
|
||
internal fun runWithArgs(args: Array<String>, parse: (Array<String>) -> Pair<KSPConfig, List<String>>) { | ||
val logger = KspGradleLogger(KspGradleLogger.LOGGING_LEVEL_WARN) | ||
val (config, classpath) = parse(args) | ||
val processorClassloader = URLClassLoader(classpath.map { File(it).toURI().toURL() }.toTypedArray()) | ||
|
||
val processorProviders = ServiceLoader.load( | ||
processorClassloader.loadClass("com.google.devtools.ksp.processing.SymbolProcessorProvider"), | ||
processorClassloader | ||
).toList() as List<SymbolProcessorProvider> | ||
|
||
KotlinSymbolProcessing(config, processorProviders, logger).execute() | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
any context on the compiler version update?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bumped to be used with the latest KSP.