diff --git a/.gitattributes b/.gitattributes
index 0ceb8a9..9356af0 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,18 +1,34 @@
-# Auto detect text files and perform LF normalization
-* text=auto
-*.bat text=crlf
+* text=auto eol=lf
+# Force Batch files to CRLF
+*.bat eol=crlf -text
-# Custom for Visual Studio
-*.cs diff=csharp
+# Java sources
+*.java text diff=java
+*.kt text diff=java
+*.gradle text diff=java
+*.gradle.kts text diff=java
-# Standard to msysgit
-*.doc diff=astextplain
-*.DOC diff=astextplain
-*.docx diff=astextplain
-*.DOCX diff=astextplain
-*.dot diff=astextplain
-*.DOT diff=astextplain
-*.pdf diff=astextplain
-*.PDF diff=astextplain
-*.rtf diff=astextplain
-*.RTF diff=astextplain
+# These files are text and should be normalized (Convert crlf => lf)
+*.css text diff=css
+*.df text
+*.htm text diff=html
+*.html text diff=html
+*.js text
+*.jsp text
+*.jspf text
+*.jspx text
+*.properties text
+*.tld text
+*.tag text
+*.tagx text
+*.xml text
+
+# These files are binary and should be left untouched
+# (binary is a macro for -text -diff)
+*.class binary
+*.dll binary
+*.ear binary
+*.jar binary
+*.so binary
+*.war binary
+*.jks binary
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 0f35681..9a9297a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,50 @@
-# gradle
.gradle/
+.kotlin/
build/
-libs/
+!gradle/wrapper/gradle-wrapper.jar
+!**/src/main/**/build/
+!**/src/test/**/build/
-*.log*
+### IntelliJ IDEA ###
+.fleet/
+.idea/
+*.iws
+*.iml
+*.ipr
+out/
+!**/src/main/**/out/
+!**/src/test/**/out/
+
+### Eclipse ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+bin/
+!**/src/main/**/bin/
+!**/src/test/**/bin/
+
+### NetBeans ###
+nbproject/
+nbbuild/
+nbdist/
+dist/
+!**/src/main/**/dist/
+!**/src/test/**/dist/
+.nb-gradle/
+
+### VS Code ###
+.vscode/
+
+### Vim ###
+.*.sw[a-p]
+
+### Mac OS ###
+.DS_Store
+.DS_Store/
+
+### Linux ###
+*~
\ No newline at end of file
diff --git a/README.md b/README.md
index bb647e2..d7bae31 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,9 @@ A generic command system, with tie-ins to many Minecraft platforms such as Bukki
Forge, and Sponge.
### Experimental Status
-Piston is, as indicated by the Semantic Version, experimental, and all APIs are subject to break on minor version changes.
+
+Piston is, as indicated by the Semantic Version, experimental, and all APIs are subject to break on minor version
+changes.
It is recommended to not use Piston in the wild.

diff --git a/build-logic/build.gradle.kts b/build-logic/build.gradle.kts
new file mode 100644
index 0000000..5ab7883
--- /dev/null
+++ b/build-logic/build.gradle.kts
@@ -0,0 +1,16 @@
+plugins {
+ `kotlin-dsl`
+}
+
+repositories {
+ gradlePluginPortal()
+ maven {
+ name = "EngineHub Repository"
+ url = uri("https://maven.enginehub.org/repo/")
+ }
+}
+
+dependencies {
+ implementation(libs.levelHeadered)
+ implementation(libs.jfrog.buildinfo)
+}
\ No newline at end of file
diff --git a/build-logic/settings.gradle.kts b/build-logic/settings.gradle.kts
new file mode 100644
index 0000000..fa8bc74
--- /dev/null
+++ b/build-logic/settings.gradle.kts
@@ -0,0 +1,7 @@
+dependencyResolutionManagement {
+ versionCatalogs {
+ create("libs") {
+ from(files("../gradle/libs.versions.toml"))
+ }
+ }
+}
\ No newline at end of file
diff --git a/build-logic/src/main/kotlin/buildlogic.artifactory.gradle.kts b/build-logic/src/main/kotlin/buildlogic.artifactory.gradle.kts
new file mode 100644
index 0000000..c53c253
--- /dev/null
+++ b/build-logic/src/main/kotlin/buildlogic.artifactory.gradle.kts
@@ -0,0 +1,39 @@
+import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
+import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
+
+plugins {
+ id("maven-publish")
+ id("com.jfrog.artifactory")
+}
+
+val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
+val ARTIFACTORY_USER = "artifactory_user"
+val ARTIFACTORY_PASSWORD = "artifactory_password"
+
+if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost"
+if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest"
+if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = ""
+
+configure {
+ setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}")
+ clientConfig.publisher.run {
+ repoKey = when {
+ "${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local"
+ else -> "libs-release-local"
+ }
+ username = "${project.property(ARTIFACTORY_USER)}"
+ password = "${project.property(ARTIFACTORY_PASSWORD)}"
+ isMaven = true
+ isIvy = false
+ }
+ publish {
+ defaults {
+ publications("maven")
+ setPublishArtifacts(true)
+ }
+ }
+}
+
+tasks.named("artifactoryPublish") {
+ skip = true
+}
\ No newline at end of file
diff --git a/build-logic/src/main/kotlin/buildlogic.common.gradle.kts b/build-logic/src/main/kotlin/buildlogic.common.gradle.kts
new file mode 100644
index 0000000..fb7cac7
--- /dev/null
+++ b/build-logic/src/main/kotlin/buildlogic.common.gradle.kts
@@ -0,0 +1,132 @@
+import buildlogic.getLibrary
+import buildlogic.stringyLibs
+import net.octyl.levelheadered.LevelHeaderedExtension
+import org.gradle.plugins.ide.idea.model.IdeaModel
+
+plugins {
+ id("eclipse")
+ id("idea")
+ id("net.octyl.level-headered")
+ id("checkstyle")
+ id("java-library")
+ id("maven-publish")
+}
+
+group = rootProject.group
+version = rootProject.version
+
+configurations.all {
+ resolutionStrategy {
+ cacheChangingModulesFor(1, TimeUnit.DAYS)
+ }
+}
+
+dependencies {
+ for (conf in listOf("implementation", "api")) {
+ if (!configurations.names.contains(conf)) {
+ continue
+ }
+
+ add(conf, platform(stringyLibs.getLibrary("log4j-bom")).map {
+ val dep = create(it)
+ dep.because("Mojang provides Log4j")
+ dep
+ })
+
+ constraints {
+ add(conf, stringyLibs.getLibrary("guava")) {
+ because("Mojang provides Guava")
+ }
+ add(conf, stringyLibs.getLibrary("gson")) {
+ because("Mojang provides Gson")
+ }
+ add(conf, stringyLibs.getLibrary("fastutil")) {
+ because("Mojang provides FastUtil")
+ }
+ }
+ }
+
+ "api"(stringyLibs.getLibrary("jsr305"))
+ "testImplementation"(platform(stringyLibs.getLibrary("junit-bom")))
+ "testImplementation"(stringyLibs.getLibrary("junit-jupiter-api"))
+ "testImplementation"(stringyLibs.getLibrary("junit-jupiter-params"))
+ "testImplementation"(platform(stringyLibs.getLibrary("mockito-bom")))
+ "testImplementation"(stringyLibs.getLibrary("mockito-core"))
+ "testImplementation"(stringyLibs.getLibrary("mockito-junit-jupiter"))
+ "testRuntimeOnly"(stringyLibs.getLibrary("junit-jupiter-engine"))
+ "testRuntimeOnly"(stringyLibs.getLibrary("junit-platform-launcher"))
+}
+
+configure {
+ headerTemplate(rootProject.file("HEADER.txt"))
+}
+
+configure {
+ configFile = rootProject.file("config/checkstyle/checkstyle.xml")
+ toolVersion = "10.16.0"
+}
+
+configure {
+ toolchain.languageVersion = JavaLanguageVersion.of(17)
+ withJavadocJar()
+ withSourcesJar()
+}
+
+configure {
+ publications {
+ register("maven") {
+ from(components["java"])
+
+ versionMapping {
+ usage("java-api") {
+ fromResolutionOf("runtimeClasspath")
+ }
+ usage("java-runtime") {
+ fromResolutionResult()
+ }
+ }
+ }
+ }
+}
+
+configure {
+ module {
+ isDownloadSources = true
+ isDownloadJavadoc = true
+ }
+}
+
+tasks {
+ withType().configureEach {
+ options.encoding = "UTF-8"
+ }
+
+ withType().configureEach {
+ useJUnitPlatform {
+ includeEngines("junit-jupiter")
+ }
+ }
+
+ // Java 8 turns on doclint which we fail
+ withType().configureEach {
+ options.encoding = "UTF-8"
+ (options as StandardJavadocDocletOptions).apply {
+ addBooleanOption("Werror", true)
+ addBooleanOption("Xdoclint:all", true)
+ addBooleanOption("Xdoclint:-missing", true)
+ tags(
+ "apiNote:a:API Note:",
+ "implSpec:a:Implementation Requirements:",
+ "implNote:a:Implementation Note:"
+ )
+ }
+ }
+
+ named("processTestResources") {
+ from(rootProject.file("common-test-resources"))
+ }
+
+ named("check").configure {
+ dependsOn("checkstyleMain", "checkstyleTest")
+ }
+}
\ No newline at end of file
diff --git a/build-logic/src/main/kotlin/buildlogic.core-ap.gradle.kts b/build-logic/src/main/kotlin/buildlogic.core-ap.gradle.kts
new file mode 100644
index 0000000..5e9d56a
--- /dev/null
+++ b/build-logic/src/main/kotlin/buildlogic.core-ap.gradle.kts
@@ -0,0 +1,5 @@
+plugins {
+ id("buildlogic.common")
+}
+
+group = "${group}.core-ap"
\ No newline at end of file
diff --git a/build-logic/src/main/kotlin/buildlogic/GradleExtras.kt b/build-logic/src/main/kotlin/buildlogic/GradleExtras.kt
new file mode 100644
index 0000000..4242800
--- /dev/null
+++ b/build-logic/src/main/kotlin/buildlogic/GradleExtras.kt
@@ -0,0 +1,19 @@
+package buildlogic
+
+import org.gradle.api.Project
+import org.gradle.api.artifacts.MinimalExternalModuleDependency
+import org.gradle.api.artifacts.VersionCatalog
+import org.gradle.api.artifacts.VersionCatalogsExtension
+import org.gradle.api.plugins.ExtraPropertiesExtension
+import org.gradle.api.provider.Provider
+import org.gradle.kotlin.dsl.getByType
+
+val Project.ext: ExtraPropertiesExtension
+ get() = extensions.getByType()
+
+val Project.stringyLibs: VersionCatalog
+ get() = extensions.getByType().named("libs")
+
+fun VersionCatalog.getLibrary(name: String): Provider = findLibrary(name).orElseThrow {
+ error("Library $name not found in version catalog")
+}
\ No newline at end of file
diff --git a/build.gradle.kts b/build.gradle.kts
index 595a3db..7b3115d 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -1,47 +1,32 @@
plugins {
- id("net.researchgate.release") version "3.0.2"
- id("org.enginehub.codecov")
jacoco
-}
-
-configureArtifactory()
-
-repositories {
- mavenCentral()
-}
-
-release {
- tagTemplate = "v\${version}"
- buildTasks = listOf()
- git.requireBranch = "master"
+ id("buildlogic.common")
+ id("buildlogic.artifactory")
}
val totalReport = tasks.register("jacocoTotalReport") {
- subprojects.forEach { proj ->
- proj.plugins.withId("java") {
- executionData(
- fileTree(proj.layout.buildDirectory.get().asFile.absolutePath).include("**/jacoco/*.exec")
- )
+ for (proj in subprojects) {
+ proj.apply(plugin = "jacoco")
+ proj.plugins.withType {
+ executionData(fileTree(proj.layout.buildDirectory).include("**/jacoco/*.exec"))
sourceSets(proj.the().sourceSets["main"])
reports {
- xml.required = true
- xml.outputLocation = rootProject.layout.buildDirectory.file("reports/jacoco/report.xml")
- html.required = true
+ xml.required.set(true)
+ xml.outputLocation.set(rootProject.layout.buildDirectory.file("reports/jacoco/report.xml"))
+ html.required.set(true)
}
dependsOn(proj.tasks.named("test"))
}
}
}
+
afterEvaluate {
totalReport.configure {
classDirectories.setFrom(classDirectories.files.map {
fileTree(it).apply {
exclude("**/*AutoValue_*")
+ exclude("**/*Registration.*")
}
})
}
-}
-
-codecov {
- reportTask.set(totalReport)
-}
+}
\ No newline at end of file
diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts
deleted file mode 100644
index b6f84aa..0000000
--- a/buildSrc/build.gradle.kts
+++ /dev/null
@@ -1,21 +0,0 @@
-plugins {
- `kotlin-dsl`
- kotlin("jvm") version embeddedKotlinVersion
-}
-
-repositories {
- mavenCentral()
- gradlePluginPortal()
- maven {
- name = "EngineHub Repository"
- url = uri("https://maven.enginehub.org/repo/")
- }
-}
-
-dependencies {
- implementation(gradleApi())
- implementation(gradleKotlinDsl())
- implementation("org.enginehub.gradle:gradle-codecov-plugin:0.2.1-SNAPSHOT")
- implementation("gradle.plugin.org.cadixdev.gradle:licenser:0.6.1")
- implementation("org.jfrog.buildinfo:build-info-extractor-gradle:5.1.14")
-}
diff --git a/buildSrc/src/main/kotlin/Libs.kt b/buildSrc/src/main/kotlin/Libs.kt
deleted file mode 100644
index c4660dd..0000000
--- a/buildSrc/src/main/kotlin/Libs.kt
+++ /dev/null
@@ -1,23 +0,0 @@
-object Libs {
- private const val junitVersion = "5.10.3"
- const val junitApi = "org.junit.jupiter:junit-jupiter-api:$junitVersion"
- const val junitEngine = "org.junit.jupiter:junit-jupiter-engine:$junitVersion"
- const val junitVintageEngine = "org.junit.vintage:junit-vintage-engine:$junitVersion"
- const val guava = "com.google.guava:guava:32.1.3-jre"
- private const val kyoriTextVersion = "3.0.4"
- const val kyoriText = "net.kyori:text-api:$kyoriTextVersion"
- const val kyoriTextPlain = "net.kyori:text-serializer-plain:$kyoriTextVersion"
- const val autoCommon = "com.google.auto:auto-common:1.2.2"
- private const val autoValueVersion = "1.11.0"
- const val autoValueAnnotations = "com.google.auto.value:auto-value-annotations:$autoValueVersion"
- const val autoValueProcessor = "com.google.auto.value:auto-value:$autoValueVersion"
- const val autoService = "com.google.auto.service:auto-service:1.1.1"
- const val javapoet = "com.squareup:javapoet:1.13.0"
- // Sync with Mojang's Log4j
- private const val log4jVersion = "2.19.0"
- const val log4jApi = "org.apache.logging.log4j:log4j-api:$log4jVersion"
- const val log4jCore = "org.apache.logging.log4j:log4j-core:$log4jVersion"
- const val javaxAnnotations = "com.google.code.findbugs:jsr305:3.0.2"
- const val compileTesting = "com.google.testing.compile:compile-testing:0.21.0"
- const val mockito = "org.mockito:mockito-core:5.12.0"
-}
diff --git a/buildSrc/src/main/kotlin/common.kt b/buildSrc/src/main/kotlin/common.kt
deleted file mode 100644
index 4709483..0000000
--- a/buildSrc/src/main/kotlin/common.kt
+++ /dev/null
@@ -1,142 +0,0 @@
-import org.cadixdev.gradle.licenser.LicenseExtension
-import org.gradle.api.JavaVersion
-import org.gradle.api.Project
-import org.gradle.api.plugins.JavaPluginExtension
-import org.gradle.api.publish.PublishingExtension
-import org.gradle.api.publish.maven.MavenPublication
-import org.gradle.api.tasks.Copy
-import org.gradle.api.tasks.SourceSetContainer
-import org.gradle.api.tasks.bundling.Jar
-import org.gradle.api.tasks.compile.JavaCompile
-import org.gradle.api.tasks.javadoc.Javadoc
-import org.gradle.api.tasks.testing.Test
-import org.gradle.external.javadoc.CoreJavadocOptions
-import org.gradle.jvm.toolchain.JavaLanguageVersion
-import org.gradle.kotlin.dsl.apply
-import org.gradle.kotlin.dsl.configure
-import org.gradle.kotlin.dsl.delegateClosureOf
-import org.gradle.kotlin.dsl.dependencies
-import org.gradle.kotlin.dsl.get
-import org.gradle.kotlin.dsl.named
-import org.gradle.kotlin.dsl.register
-import org.gradle.kotlin.dsl.repositories
-import org.gradle.kotlin.dsl.the
-import org.gradle.kotlin.dsl.withType
-import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
-import org.jfrog.gradle.plugin.artifactory.dsl.PublisherConfig
-import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
-
-fun Project.applyCommonConfig(
- group: String = rootProject.group.toString()
-) {
- apply(plugin = "java-library")
- apply(plugin = "java")
- apply(plugin = "org.cadixdev.licenser")
- apply(plugin = "maven-publish")
- apply(plugin = "com.jfrog.artifactory")
- apply(plugin = "jacoco")
-
- project.group = group
-
- configure {
- setHeader(rootProject.file("HEADER.txt"))
- exclude("**/META-INF/**")
- exclude("**/*.properties")
- }
-
- tasks.withType().configureEach {
- useJUnitPlatform()
- }
-
- repositories {
- mavenCentral()
- }
-
- tasks.named("processTestResources") {
- from(rootProject.file("common-test-resources"))
- }
-
- configure {
- toolchain.languageVersion.set(JavaLanguageVersion.of(17))
- }
- tasks.named("compileJava") {
- options.encoding = "UTF-8"
- }
- tasks.named("compileTestJava") {
- options.encoding = "UTF-8"
- }
- tasks.withType().configureEach {
- (options as CoreJavadocOptions).addStringOption("Xdoclint:none", "-quiet")
- }
-
- dependencies {
- "testImplementation"(Libs.junitApi)
- "testImplementation"(Libs.junitEngine)
- }
-
- addExtraArchiveArtifacts()
-
- configureMavenPublish()
-
- val build = tasks.named("build")
- rootProject.tasks.named("afterReleaseBuild").configure {
- dependsOn(build)
- }
-}
-
-private fun Project.addExtraArchiveArtifacts() {
- configure {
- withSourcesJar()
- withJavadocJar()
- }
-}
-
-private fun Project.configureMavenPublish() {
- configure {
- publications {
- register("maven") {
- groupId = project.group.toString()
- artifactId = project.name
- version = project.version.toString()
-
- from(components["java"])
- }
- }
- }
-}
-
-fun Project.configureArtifactory() {
- apply(plugin = "maven-publish")
- apply(plugin = "com.jfrog.artifactory")
- val ext = extensions.extraProperties
- if (!project.hasProperty("artifactory_contextUrl"))
- ext["artifactory_contextUrl"] = "http://localhost"
- if (!project.hasProperty("artifactory_user"))
- ext["artifactory_user"] = "guest"
- if (!project.hasProperty("artifactory_password"))
- ext["artifactory_password"] = ""
- configure {
- publish {
- contextUrl = project.property("artifactory_contextUrl").toString()
- repository {
- repoKey = when {
- "SNAPSHOT" in project.version.toString() -> "libs-snapshot-local"
- else -> "libs-release-local"
- }
- username = project.property("artifactory_user").toString()
- password = project.property("artifactory_password").toString()
- }
- defaults {
- publications("maven")
- setPublishArtifacts(true)
- }
- }
- }
- tasks.named("artifactoryPublish") {
- skip = true
- }
-}
-
-fun Project.applyCoreApConfig() {
- applyCommonConfig(group = rootProject.group.toString() + ".core-ap")
-}
diff --git a/common-test-resources/junit-platform.properties b/common-test-resources/junit-platform.properties
index 4fba76b..6b92307 100644
--- a/common-test-resources/junit-platform.properties
+++ b/common-test-resources/junit-platform.properties
@@ -1,6 +1,5 @@
-junit.jupiter.execution.parallel.enabled = true
-junit.jupiter.execution.parallel.mode.default = concurrent
-junit.jupiter.execution.parallel.mode.classes.default = concurrent
-junit.jupiter.execution.parallel.config.strategy = dynamic
-
-junit.jupiter.extensions.autodetection.enabled = true
\ No newline at end of file
+junit.jupiter.execution.parallel.enabled=true
+junit.jupiter.execution.parallel.mode.default=concurrent
+junit.jupiter.execution.parallel.mode.classes.default=concurrent
+junit.jupiter.execution.parallel.config.strategy=dynamic
+junit.jupiter.extensions.autodetection.enabled=true
\ No newline at end of file
diff --git a/config/checkstyle/checkstyle-suppression.xml b/config/checkstyle/checkstyle-suppression.xml
new file mode 100644
index 0000000..6bd14bd
--- /dev/null
+++ b/config/checkstyle/checkstyle-suppression.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml
new file mode 100644
index 0000000..dd64c18
--- /dev/null
+++ b/config/checkstyle/checkstyle.xml
@@ -0,0 +1,202 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-ap/annotations/build.gradle.kts b/core-ap/annotations/build.gradle.kts
index 5c33ba3..55984ba 100644
--- a/core-ap/annotations/build.gradle.kts
+++ b/core-ap/annotations/build.gradle.kts
@@ -1,4 +1,6 @@
-applyCoreApConfig()
+plugins {
+ id("buildlogic.core-ap")
+}
dependencies {
"api"(project(":core"))
diff --git a/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/CommandContainer.java b/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/CommandContainer.java
index d60c882..0371b7b 100644
--- a/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/CommandContainer.java
+++ b/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/CommandContainer.java
@@ -37,22 +37,16 @@
/**
* Super-types for the generated registration class to implement.
*
- *
- * Note that this does not force the class to implement new methods,
+ *
Note that this does not force the class to implement new methods,
* but if you add an interface that matches existing methods, then
- * those will be overriden, allowing for more generic configuration.
- *
- *
- * For example, you could add an interface representing the addition
+ * those will be overridden, allowing for more generic configuration.
+ *
+ * For example, you could add an interface representing the addition
* of a {@link CommandConditionGenerator} to the registration builder,
- * and then you will be able to inject all builders using a single method.
- *
- *
- * N.B.: The registration class always implements {@link CommandRegistration},
- * regardless of the content of this array.
- *
+ * and then you will be able to inject all builders using a single method.
*
* @return the super-types for the generated registration class
+ * @implNote The registration class always implements {@link CommandRegistration}, regardless of the content of this array.
*/
Class>[] superTypes() default {};
diff --git a/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/param/ArgFlag.java b/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/param/ArgFlag.java
index bcdafbb..70a33c0 100644
--- a/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/param/ArgFlag.java
+++ b/core-ap/annotations/src/main/java/org/enginehub/piston/annotation/param/ArgFlag.java
@@ -33,13 +33,13 @@
@Retention(RetentionPolicy.CLASS)
public @interface ArgFlag {
+ String ARG_NAME_IS_PARAMETER_NAME = "__ARG_NAME_IS_PARAMETER_NAME__";
+
/**
* The name of the flag.
*/
char name();
- String ARG_NAME_IS_PARAMETER_NAME = "__ARG_NAME_IS_PARAMETER_NAME__";
-
/**
* The name of the argument. If not specified, defaults to the name of
* the parameter.
diff --git a/core-ap/processor/build.gradle.kts b/core-ap/processor/build.gradle.kts
index 35bd63f..d480120 100644
--- a/core-ap/processor/build.gradle.kts
+++ b/core-ap/processor/build.gradle.kts
@@ -1,45 +1,45 @@
plugins {
- kotlin("jvm") version "2.0.0"
- kotlin("kapt") version "2.0.0"
+ kotlin("jvm") version "2.3.0"
+ kotlin("kapt") version "2.3.0"
+ id("buildlogic.core-ap")
}
-applyCoreApConfig()
-
kapt.includeCompileClasspath = false
tasks.test {
// Crack open the compiler for compile testing
- jvmArgs(
- "--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
- "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
- "--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED",
- )
+ listOf(
+ "api",
+ "file",
+ "main",
+ "parser",
+ "tree",
+ "util"
+ ).forEach { jvmArgs("--add-exports=jdk.compiler/com.sun.tools.javac.${it}=ALL-UNNAMED") }
}
dependencies {
"implementation"(project(":core"))
"implementation"(project(":core-ap:annotations"))
"implementation"(project(":core-ap:runtime"))
- "implementation"(Libs.guava)
- "implementation"(Libs.javapoet)
- "implementation"(Libs.autoCommon)
- "compileOnly"(Libs.autoValueAnnotations)
- "kapt"(Libs.autoValueProcessor)
- "compileOnly"(Libs.autoService)
- "kapt"(Libs.autoService)
+ "implementation"(libs.guava)
+ "implementation"(libs.javapoet)
+ "implementation"(libs.autoCommon)
+ "compileOnly"(libs.autoValue.annotations)
+ "kapt"(libs.autoValue)
+ "compileOnly"(libs.autoService)
+ "kapt"(libs.autoService)
"testImplementation"(kotlin("stdlib-jdk8"))
- "testRuntimeOnly"(Libs.junitVintageEngine)
- "testImplementation"(Libs.compileTesting) {
+ "testImplementation"(libs.compileTesting) {
exclude("junit", "junit")
}
- "testImplementation"(Libs.guava)
+ "testImplementation"(libs.guava)
- "testImplementation"(Libs.mockito)
- "testRuntimeOnly"(Libs.log4jCore)
+ "testRuntimeOnly"(libs.log4j.core)
"testImplementation"(project(":default-impl"))
- "testCompileOnly"(Libs.autoService)
- "kaptTest"(Libs.autoService)
+ "testCompileOnly"(libs.autoService)
+ "kaptTest"(libs.autoService)
"kaptTest"(project(":core-ap:processor"))
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandParameterInterpreter.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandParameterInterpreter.java
index 10b1324..549a683 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandParameterInterpreter.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandParameterInterpreter.java
@@ -22,10 +22,10 @@
import com.google.auto.common.MoreElements;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.squareup.javapoet.AnnotationSpec;
-import com.squareup.javapoet.ClassName;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.AnnotationSpec;
+import com.palantir.javapoet.ClassName;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.TypeName;
import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.CommandValue;
import org.enginehub.piston.annotation.param.Arg;
@@ -43,6 +43,10 @@
import org.enginehub.piston.part.CommandParts;
import org.enginehub.piston.part.NoArgCommandFlag;
+import java.lang.annotation.Annotation;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
@@ -50,10 +54,6 @@
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
-import java.lang.annotation.Annotation;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
import static com.google.auto.common.MoreElements.asType;
import static com.google.auto.common.MoreElements.getAnnotationMirror;
@@ -70,25 +70,14 @@
class CommandParameterInterpreter {
- private interface ParamTransform {
-
- CommandParamInfo createPartInfo(VariableElement parameter);
-
- }
-
- private static boolean isUnconverted(ProcessingEnvironment env, VariableElement parameter) {
- TypeMirror commandValue = env.getElementUtils().getTypeElement(CommandValue.class.getCanonicalName()).asType();
- return env.getTypeUtils().isAssignable(parameter.asType(), commandValue);
- }
-
- private final Map, ParamTransform> ANNOTATION_TRANSFORMS = ImmutableMap.of(
+ private final ExecutableElement method;
+ private final GenerationSupport generationSupport;
+ private final ProcessingEnvironment env;
+ private final Map, ParamTransform> annotationTransforms = ImmutableMap.of(
Arg.class, this::argTransform,
ArgFlag.class, this::argFlagTransform,
Switch.class, this::switchTransform
);
- private final ExecutableElement method;
- private final GenerationSupport generationSupport;
- private final ProcessingEnvironment env;
CommandParameterInterpreter(ExecutableElement method,
GenerationSupport generationSupport,
@@ -98,6 +87,11 @@ private static boolean isUnconverted(ProcessingEnvironment env, VariableElement
this.env = env;
}
+ private static boolean isUnconverted(ProcessingEnvironment env, VariableElement parameter) {
+ TypeMirror commandValue = env.getElementUtils().getTypeElement(CommandValue.class.getCanonicalName()).asType();
+ return env.getTypeUtils().isAssignable(parameter.asType(), commandValue);
+ }
+
private CommandParamInfo argTransform(VariableElement parameter) {
AnnotationMirror arg = MoreElements.getAnnotationMirror(parameter, Arg.class)
.toJavaUtil().orElseThrow(() ->
@@ -109,8 +103,10 @@ private CommandParamInfo argTransform(VariableElement parameter) {
String desc = getValue(parameter, arg, "desc", String.class);
List defaults = getList(parameter, arg, "def", String.class);
CodeBlock.Builder construction = CodeBlock.builder()
- .add("$T.arg($L, $L)\n" +
- ".defaultsTo($L)\n",
+ .add("""
+ $T.arg($L, $L)
+ .defaultsTo($L)
+ """,
CommandParts.class, transCompOf(prefixArgName(env, name)), textCompOf(desc),
stringListForGen(defaults.stream()));
addArgTypes(parameter, construction);
@@ -138,10 +134,12 @@ private CommandParamInfo argFlagTransform(VariableElement parameter) {
String desc = getValue(parameter, arg, "desc", String.class);
List defaults = getList(parameter, arg, "def", String.class);
CodeBlock.Builder construction = CodeBlock.builder()
- .add("$T.flag('$L', $L)\n" +
- ".withRequiredArg()\n" +
- ".argNamed($L)\n" +
- ".defaultsTo($L)\n",
+ .add("""
+ $T.flag('$L', $L)
+ .withRequiredArg()
+ .argNamed($L)
+ .defaultsTo($L)
+ """,
CommandParts.class, name, textCompOf(desc),
transCompOf(prefixArgName(env, argName)),
stringListForGen(defaults.stream()));
@@ -172,7 +170,7 @@ private void addArgTypes(VariableElement parameter, CodeBlock.Builder constructi
private ExtractSpec getArgExtractSpec(VariableElement parameter) {
TypeMirror parameterType = parameter.asType();
return ExtractSpec.builder()
- .name("extract$" + parameter.getSimpleName().toString())
+ .name("extract$" + parameter.getSimpleName())
.type(TypeName.get(parameterType))
.extractMethodBody(var -> {
CodeBlock.Builder builder = CodeBlock.builder();
@@ -221,7 +219,7 @@ private CommandParamInfo switchTransform(VariableElement parameter) {
"$T.flag('$L', $L).build()",
CommandParts.class, name, textCompOf(desc)))
.extractSpec(ExtractSpec.builder()
- .name("extract$" + parameter.getSimpleName().toString())
+ .name("extract$" + parameter.getSimpleName())
.type(TypeName.get(parameter.asType()))
.extractMethodBody(var -> CodeBlock.builder()
.addStatement("return $L.in($L)",
@@ -241,7 +239,7 @@ private CommandParamInfo untransformedParameter(VariableElement parameter) {
private CommandParamInfo commandParameterValue(VariableElement parameter) {
return CommandParamInfo.builder()
.extractSpec(ExtractSpec.builder()
- .name("extract$" + parameter.getSimpleName().toString())
+ .name("extract$" + parameter.getSimpleName())
.type(TypeName.get(parameter.asType()))
.extractMethodBody(var ->
CodeBlock.of("$[return $L;\n$]", ReservedNames.PARAMETERS))
@@ -252,7 +250,7 @@ private CommandParamInfo commandParameterValue(VariableElement parameter) {
private CommandParamInfo injectableValue(VariableElement parameter) {
return CommandParamInfo.builder()
.extractSpec(ExtractSpec.builder()
- .name("extract$" + parameter.getSimpleName().toString())
+ .name("extract$" + parameter.getSimpleName())
.type(TypeName.get(parameter.asType()))
.extractMethodBody(var -> {
CodeBlock paramKey = asKeyType(parameter);
@@ -298,7 +296,7 @@ List getParams() {
private CommandParamInfo getParam(VariableElement parameter) {
ImmutableList transforms =
- ANNOTATION_TRANSFORMS.entrySet().stream()
+ annotationTransforms.entrySet().stream()
.filter(e -> isAnnotationPresent(parameter, e.getKey()))
.map(Map.Entry::getValue)
.collect(toImmutableList());
@@ -310,4 +308,10 @@ private CommandParamInfo getParam(VariableElement parameter) {
ParamTransform transform = transforms.isEmpty() ? this::untransformedParameter : transforms.get(0);
return transform.createPartInfo(parameter);
}
+
+ private interface ParamTransform {
+
+ CommandParamInfo createPartInfo(VariableElement parameter);
+
+ }
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandProcessor.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandProcessor.java
index 1f69015..00ed9bd 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandProcessor.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandProcessor.java
@@ -30,7 +30,7 @@
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Sets;
-import com.squareup.javapoet.ClassName;
+import com.palantir.javapoet.ClassName;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandCondition;
import org.enginehub.piston.annotation.CommandContainer;
@@ -74,6 +74,32 @@
@SupportedOptions(ARG_NAME_KEY_PREFIX)
public class CommandProcessor extends BasicAnnotationProcessor {
+ private static final ImmutableSet VISIBILITY_MODIFIERS = Sets.immutableEnumSet(
+ Modifier.PUBLIC,
+ Modifier.PROTECTED,
+ Modifier.PRIVATE
+ );
+ private static final LoadingCache IS_CONDITION =
+ CacheBuilder.newBuilder()
+ .weakKeys()
+ // take 50 falses, or many more trues
+ // we value a positive result more
+ .maximumWeight(5000)
+ .weigher((k, v) -> v ? 1 : 100)
+ .build(CacheLoader.from((TypeElement element) -> {
+ if (element == null) {
+ return false;
+ }
+ if (isExactlyConditionAnno(element)) {
+ return true;
+ }
+ return isAnnotationPresent(element, CommandCondition.class);
+ }));
+
+ private static boolean isExactlyConditionAnno(TypeElement element) {
+ return element.getQualifiedName().contentEquals(CommandCondition.class.getCanonicalName());
+ }
+
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
@@ -175,12 +201,6 @@ private CommandInfoOptimization buildOptimizer(IdentifierTracker identifierTrack
identifierTracker);
}
- private static final ImmutableSet VISIBILITY_MODIFIERS = Sets.immutableEnumSet(
- Modifier.PUBLIC,
- Modifier.PROTECTED,
- Modifier.PRIVATE
- );
-
@Nullable
private Modifier visibility(Set modifiers) {
return modifiers.stream()
@@ -222,27 +242,6 @@ private CommandInfo getCommandInfo(ExecutableElement method, GenerationSupport g
.build();
}
- private final LoadingCache IS_CONDITION =
- CacheBuilder.newBuilder()
- .weakKeys()
- // take 50 falses, or many more trues
- // we value a positive result more
- .maximumWeight(5000)
- .weigher((k, v) -> v ? 1 : 100)
- .build(CacheLoader.from((TypeElement element) -> {
- if (element == null) {
- return false;
- }
- if (isExactlyConditionAnno(element)) {
- return true;
- }
- return isAnnotationPresent(element, CommandCondition.class);
- }));
-
- private static boolean isExactlyConditionAnno(TypeElement element) {
- return element.getQualifiedName().contentEquals(CommandCondition.class.getCanonicalName());
- }
-
private Optional findCommandCondition(ExecutableElement method) {
return method.getAnnotationMirrors().stream()
.filter(mirror -> IS_CONDITION.getUnchecked(
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandRegistrationGenerator.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandRegistrationGenerator.java
index ba6cfdc..95e24de 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandRegistrationGenerator.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/CommandRegistrationGenerator.java
@@ -20,16 +20,16 @@
package org.enginehub.piston.gen;
import com.google.common.collect.ImmutableList;
-import com.squareup.javapoet.AnnotationSpec;
-import com.squareup.javapoet.ClassName;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.FieldSpec;
-import com.squareup.javapoet.JavaFile;
-import com.squareup.javapoet.MethodSpec;
-import com.squareup.javapoet.ParameterSpec;
-import com.squareup.javapoet.ParameterizedTypeName;
-import com.squareup.javapoet.TypeName;
-import com.squareup.javapoet.TypeSpec;
+import com.palantir.javapoet.AnnotationSpec;
+import com.palantir.javapoet.ClassName;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.FieldSpec;
+import com.palantir.javapoet.JavaFile;
+import com.palantir.javapoet.MethodSpec;
+import com.palantir.javapoet.ParameterSpec;
+import com.palantir.javapoet.ParameterizedTypeName;
+import com.palantir.javapoet.TypeName;
+import com.palantir.javapoet.TypeSpec;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.gen.util.CodeBlockUtil;
@@ -43,12 +43,6 @@
import org.enginehub.piston.internal.RegistrationUtil;
import org.enginehub.piston.part.CommandParts;
-import javax.annotation.processing.Filer;
-import javax.lang.model.element.Element;
-import javax.lang.model.element.ElementKind;
-import javax.lang.model.element.Modifier;
-import javax.lang.model.element.TypeElement;
-import javax.lang.model.type.TypeMirror;
import java.io.IOException;
import java.lang.reflect.Method;
import java.time.Instant;
@@ -56,6 +50,12 @@
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Stream;
+import javax.annotation.processing.Filer;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.TypeMirror;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
@@ -80,8 +80,6 @@
*
*/
class CommandRegistrationGenerator {
- private static final ParameterSpec COMMAND_PARAMETERS_SPEC
- = ParameterSpec.builder(CommandParameters.class, "parameters").build();
public static final RequiredVariable LISTENERS_REQ_VAR = RequiredVariable.builder()
.name(ReservedNames.LISTENERS)
.type(ParameterizedTypeName.get(
@@ -90,17 +88,11 @@ class CommandRegistrationGenerator {
))
.inherited(true)
.build();
+ private static final ParameterSpec COMMAND_PARAMETERS_SPEC
+ = ParameterSpec.builder(CommandParameters.class, "parameters").build();
private final RegistrationInfo info;
private final ImmutableList injectedVariables;
- private static boolean isStaticImportable(Method method) {
- int mods = method.getModifiers();
- if (!java.lang.reflect.Modifier.isStatic(mods)) {
- return false;
- }
- return !method.isSynthetic();
- }
-
CommandRegistrationGenerator(RegistrationInfo info) {
this.info = info;
this.injectedVariables = concat(
@@ -109,8 +101,12 @@ private static boolean isStaticImportable(Method method) {
).collect(toImmutableList());
}
- private Stream cmdsFlatMap(Function> map) {
- return info.getCommands().stream().flatMap(map);
+ private static boolean isStaticImportable(Method method) {
+ int mods = method.getModifiers();
+ if (!java.lang.reflect.Modifier.isStatic(mods)) {
+ return false;
+ }
+ return !method.isSynthetic();
}
private static Stream additionalVariables(RegistrationInfo info) {
@@ -128,14 +124,18 @@ private static Stream additionalVariables(RegistrationInfo inf
return b.build();
}
- private Stream getInjectedVariables() {
- return injectedVariables.stream();
- }
-
private static boolean isCommandStatic(CommandInfo info) {
return info.getCommandMethod().getModifiers().contains(STATIC);
}
+ private Stream cmdsFlatMap(Function> map) {
+ return info.getCommands().stream().flatMap(map);
+ }
+
+ private Stream getInjectedVariables() {
+ return injectedVariables.stream();
+ }
+
private Modifier[] getApiVisibilityModifiers() {
return info.getClassVisibility() == null
? new Modifier[0]
@@ -170,7 +170,7 @@ void generate(Element originalElement, String pkgName, Filer filer) throws IOExc
spec.addSuperinterface(TypeName.get(superType.asType()));
} else {
throw new IllegalStateException("Not a possible super-type: "
- + superType.getKind() + " " + superType.getQualifiedName().toString());
+ + superType.getKind() + " " + superType.getQualifiedName());
}
}
@@ -287,8 +287,8 @@ private Stream getPartFields() {
.filter(p -> p.getType() != null && p.getName() != null && p.getConstruction() != null)
.distinct()
.map(p -> FieldSpec.builder(
- p.getType(), p.getName(),
- PRIVATE, FINAL)
+ p.getType(), p.getName(),
+ PRIVATE, FINAL)
.initializer(CodeBlock.of("$[$L$]", p.getConstruction()))
.build());
}
@@ -374,14 +374,14 @@ private MethodSpec generateCommandBinding(CommandInfo commandInfo) {
// call afterCall
body.addStatement("$T.listenersAfterCall(listeners, cmdMethod, $L)",
- RegistrationUtil.class, ReservedNames.PARAMETERS)
+ RegistrationUtil.class, ReservedNames.PARAMETERS)
.addStatement("return result");
body.nextControlFlow("catch ($T t)", Throwable.class);
// call afterThrow & re-throw
body.addStatement("$T.listenersAfterThrow(listeners, cmdMethod, $L, t)",
- RegistrationUtil.class, ReservedNames.PARAMETERS)
+ RegistrationUtil.class, ReservedNames.PARAMETERS)
.addStatement("throw t");
body.endControlFlow();
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/ConditionGenerator.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/ConditionGenerator.java
index 953728b..f0be4ad 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/ConditionGenerator.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/ConditionGenerator.java
@@ -19,8 +19,8 @@
package org.enginehub.piston.gen;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.TypeName;
import org.enginehub.piston.Command;
import org.enginehub.piston.gen.util.CodeBlockUtil;
import org.enginehub.piston.gen.util.ProcessingException;
@@ -35,10 +35,10 @@
import static com.google.auto.common.AnnotationMirrors.getAnnotationValue;
class ConditionGenerator {
+ public static final String COMMAND_METHOD_FIELD = "commandMethod";
private final AnnotationMirror conditionMirror;
private final ExecutableElement method;
private final GenerationSupport depSupport;
- public static final String COMMAND_METHOD_FIELD = "commandMethod";
ConditionGenerator(AnnotationMirror conditionMirror,
ExecutableElement method,
@@ -52,7 +52,8 @@ CommandCondInfo generateCondition() {
TypeName generatorClassName = getAnnotationValue(conditionMirror, "value")
.accept(new SimpleAnnotationValueVisitor8() {
@Override
- public TypeName visitType(TypeMirror t, Void aVoid) {
+ public TypeName visitType(TypeMirror t, Void avoid) {
+ // Checkstyle: 'ParameterName' does not permit capitalization of second letter in [aVoid]
return TypeName.get(t);
}
}, null);
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupport.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupport.java
index f994ea0..609f608 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupport.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupport.java
@@ -19,9 +19,9 @@
package org.enginehub.piston.gen;
-import com.squareup.javapoet.AnnotationSpec;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.AnnotationSpec;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.TypeName;
import org.enginehub.piston.inject.Key;
import javax.annotation.Nullable;
@@ -39,10 +39,10 @@ public interface GenerationSupport {
* for easy injection of common dependencies, shared by multiple different code generators.
*
*
- * @param type the type of the variable
- * @param name the base name of the variable
+ * @param type the type of the variable
+ * @param name the base name of the variable
* @param shareKey if non-null, share variables that match this key, as well as type and
- * name
+ * name
* @return the actual name of the variable. You must use this to reference it.
*/
String requestDependency(TypeName type, String name, @Nullable Object shareKey);
@@ -56,10 +56,10 @@ public interface GenerationSupport {
* for easy injection of common dependencies, shared by multiple different code generators.
*
*
- * @param type the type of the field
- * @param name the requested name of the field
+ * @param type the type of the field
+ * @param name the requested name of the field
* @param shareKey if non-null, share variables that match this key, as well as type and
- * name
+ * name
* @return the actual name of the field. You must use this to reference it.
*/
String requestField(TypeName type, String name, @Nullable Object shareKey);
@@ -75,7 +75,7 @@ public interface GenerationSupport {
/**
* Request a {@link Key} that provides the type at runtime.
*
- * @param type the type to represent with a {@code Key}
+ * @param type the type to represent with a {@code Key}
* @param annotationSpec the annotation to include on the {@code Key}
* @return code that represents an expression which will return the correct {@code Key}
*/
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupportImpl.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupportImpl.java
index a23659b..cf793c4 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupportImpl.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/GenerationSupportImpl.java
@@ -19,47 +19,19 @@
package org.enginehub.piston.gen;
-import com.squareup.javapoet.AnnotationSpec;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.AnnotationSpec;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.TypeName;
import org.enginehub.piston.gen.value.KeyInfo;
import org.enginehub.piston.gen.value.RegistrationInfo;
import org.enginehub.piston.gen.value.RequiredVariable;
-import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
-import java.util.Objects;
+import javax.annotation.Nullable;
class GenerationSupportImpl implements GenerationSupport {
- private static final class ShareKey {
- private final TypeName type;
- private final String name;
- private final Object shareKey;
-
- ShareKey(TypeName type, String name, Object shareKey) {
- this.type = type;
- this.name = name;
- this.shareKey = shareKey;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- ShareKey shareKey1 = (ShareKey) o;
- return type.equals(shareKey1.type) &&
- name.equals(shareKey1.name) &&
- shareKey.equals(shareKey1.shareKey);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(type, name, shareKey);
- }
- }
-
private final IdentifierTracker identifierTracker;
private final RegistrationInfo.Builder builder;
private final Map sharedDepNames = new HashMap<>();
@@ -123,4 +95,22 @@ public CodeBlock requestKey(TypeName type, @Nullable AnnotationSpec annotationSp
builder.addKeyType(keyInfo);
return CodeBlock.of("$L", keyInfo.getVariableName());
}
+
+ private record ShareKey(TypeName type, String name, Object shareKey) {
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ShareKey shareKey1 = (ShareKey) o;
+ return type.equals(shareKey1.type)
+ && name.equals(shareKey1.name)
+ && shareKey.equals(shareKey1.shareKey);
+ }
+
+ }
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/IdentifierTracker.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/IdentifierTracker.java
index fcd403c..8500e40 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/IdentifierTracker.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/IdentifierTracker.java
@@ -26,6 +26,9 @@
public class IdentifierTracker {
+ private final Multiset fieldNames = HashMultiset.create(ReservedNames.fieldNames());
+ private final Multiset methodNames = HashMultiset.create(ReservedNames.methodNames());
+
private static String realName(Multiset memory, String name) {
// Make the name safe first
name = SafeName.from(name);
@@ -34,9 +37,6 @@ private static String realName(Multiset memory, String name) {
return count == 1 ? name : name + count;
}
- private final Multiset fieldNames = HashMultiset.create(ReservedNames.fieldNames());
- private final Multiset methodNames = HashMultiset.create(ReservedNames.methodNames());
-
public String fieldName(String requested) {
return realName(fieldNames, requested);
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/CollectionOptimization.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/CollectionOptimization.java
index 806e914..44e798f 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/CollectionOptimization.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/CollectionOptimization.java
@@ -24,8 +24,6 @@
/**
* Represents an optimization over a collection.
- *
- * @param
*/
@FunctionalInterface
public interface CollectionOptimization extends Optimization> {
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/Optimization.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/Optimization.java
index 57f31da..15e31fb 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/Optimization.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/optimize/Optimization.java
@@ -21,8 +21,6 @@
/**
* Represents an optimization.
- *
- * @param
*/
@FunctionalInterface
public interface Optimization {
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/AnnoValueExtraction.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/AnnoValueExtraction.java
index b6c6370..af40d35 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/AnnoValueExtraction.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/AnnoValueExtraction.java
@@ -22,15 +22,15 @@
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Primitives;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Predicate;
import javax.annotation.Nullable;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.AnnotationValueVisitor;
import javax.lang.model.element.Element;
import javax.lang.model.util.SimpleAnnotationValueVisitor8;
-import java.util.List;
-import java.util.Objects;
-import java.util.function.Predicate;
import static com.google.auto.common.AnnotationMirrors.getAnnotationValue;
@@ -40,18 +40,6 @@
*/
public class AnnoValueExtraction {
- private static final class GeneralResult {
- @Nullable
- private final Object good;
- @Nullable
- private final Object bad;
-
- public GeneralResult(@Nullable Object good, @Nullable Object bad) {
- this.good = good;
- this.bad = bad;
- }
- }
-
private static final AnnotationValueVisitor> GENERAL_VISITOR =
new SimpleAnnotationValueVisitor8>() {
@Override
@@ -108,4 +96,7 @@ public List visitArray(List extends AnnotationValue> vals, Void unused) {
}, null);
}
+ private record GeneralResult(@Nullable Object good, @Nullable Object bad) {
+ }
+
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/CodeBlockUtil.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/CodeBlockUtil.java
index 883150c..6546d07 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/CodeBlockUtil.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/CodeBlockUtil.java
@@ -20,18 +20,18 @@
package org.enginehub.piston.gen.util;
import com.google.common.collect.ImmutableList;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.TypeName;
import net.kyori.text.TextComponent;
import net.kyori.text.TranslatableComponent;
import org.enginehub.piston.internal.RegistrationUtil;
-import javax.annotation.Nullable;
-import javax.lang.model.element.ExecutableElement;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Stream;
+import javax.annotation.Nullable;
+import javax.lang.model.element.ExecutableElement;
import static java.util.Objects.requireNonNull;
import static org.enginehub.piston.gen.util.TypeNameUtil.rawType;
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/ProcessingEnvValues.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/ProcessingEnvValues.java
index 64c377d..78f1b70 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/ProcessingEnvValues.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/ProcessingEnvValues.java
@@ -28,11 +28,11 @@ public class ProcessingEnvValues {
public static final String ARG_NAME_KEY_PREFIX = "arg.name.key.prefix";
+ private ProcessingEnvValues() {
+ }
+
public static String prefixArgName(ProcessingEnvironment env, String name) {
String prefix = env.getOptions().getOrDefault(ARG_NAME_KEY_PREFIX, "piston.argument");
return prefix == null || prefix.isEmpty() ? name : prefix + "." + name;
}
-
- private ProcessingEnvValues() {
- }
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/SafeName.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/SafeName.java
index a1acbef..d4b90f6 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/SafeName.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/SafeName.java
@@ -19,10 +19,10 @@
package org.enginehub.piston.gen.util;
-import com.squareup.javapoet.ArrayTypeName;
-import com.squareup.javapoet.ClassName;
-import com.squareup.javapoet.ParameterizedTypeName;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.ArrayTypeName;
+import com.palantir.javapoet.ClassName;
+import com.palantir.javapoet.ParameterizedTypeName;
+import com.palantir.javapoet.TypeName;
import org.enginehub.piston.util.CaseHelper;
/**
@@ -60,20 +60,19 @@ private static CharSequence getNameAsIdentifierRaw(TypeName typeName) {
if (typeName instanceof ClassName) {
// good, just the raw name works here
return ((ClassName) typeName).simpleName();
- } else if (typeName instanceof ParameterizedTypeName) {
+ } else if (typeName instanceof ParameterizedTypeName pt) {
// append the type parameters
- ParameterizedTypeName pt = (ParameterizedTypeName) typeName;
- ClassName raw = pt.rawType;
+ ClassName raw = pt.rawType();
StringBuilder result = new StringBuilder(
getNameAsIdentifierRaw(raw)
);
- for (TypeName typeArgument : pt.typeArguments) {
+ for (TypeName typeArgument : pt.typeArguments()) {
result.append('$').append(getNameAsIdentifierRaw(typeArgument));
}
return result;
} else if (typeName instanceof ArrayTypeName) {
// append Array to the name
- CharSequence base = getNameAsIdentifierRaw(((ArrayTypeName) typeName).componentType);
+ CharSequence base = getNameAsIdentifierRaw(((ArrayTypeName) typeName).componentType());
return new StringBuilder(base).append("$Array");
}
// just use toString() as a last resort
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/TypeNameUtil.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/TypeNameUtil.java
index 7bf6efe..f42667a 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/TypeNameUtil.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/util/TypeNameUtil.java
@@ -19,35 +19,34 @@
package org.enginehub.piston.gen.util;
-import com.squareup.javapoet.ArrayTypeName;
-import com.squareup.javapoet.ClassName;
-import com.squareup.javapoet.ParameterizedTypeName;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.ArrayTypeName;
+import com.palantir.javapoet.ClassName;
+import com.palantir.javapoet.ParameterizedTypeName;
+import com.palantir.javapoet.TypeName;
public class TypeNameUtil {
+ private TypeNameUtil() {
+ }
+
public static TypeName rawType(TypeName typeName) {
if (typeName instanceof ClassName) {
return typeName;
} else if (typeName instanceof ArrayTypeName) {
- return ArrayTypeName.of(rawType(((ArrayTypeName) typeName).componentType));
+ return ArrayTypeName.of(rawType(((ArrayTypeName) typeName).componentType()));
} else if (typeName instanceof ParameterizedTypeName) {
- return ((ParameterizedTypeName) typeName).rawType;
+ return ((ParameterizedTypeName) typeName).rawType();
} else if (typeName.isPrimitive()) {
return typeName;
}
- throw new IllegalArgumentException("Not able to create a raw type from " +
- "'" + typeName + "' (" + typeName.getClass() + ")");
+ throw new IllegalArgumentException("Not able to create a raw type from '" + typeName + "' (" + typeName.getClass() + ")");
}
public static TypeName firstTypeArg(TypeName typeName) {
if (typeName instanceof ParameterizedTypeName) {
- return ((ParameterizedTypeName) typeName).typeArguments.get(0);
+ return ((ParameterizedTypeName) typeName).typeArguments().get(0);
}
- return TypeName.OBJECT;
- }
-
- private TypeNameUtil() {
+ return ClassName.OBJECT;
}
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandCondInfo.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandCondInfo.java
index d7c3c81..fba8c2a 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandCondInfo.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandCondInfo.java
@@ -20,7 +20,7 @@
package org.enginehub.piston.gen.value;
import com.google.auto.value.AutoValue;
-import com.squareup.javapoet.CodeBlock;
+import com.palantir.javapoet.CodeBlock;
/**
* Information that can be used to supply the condition for a
@@ -33,16 +33,6 @@ public static Builder builder() {
return new AutoValue_CommandCondInfo.Builder();
}
- @AutoValue.Builder
- public interface Builder {
-
- Builder condVariable(String variable);
-
- Builder construction(CodeBlock construction);
-
- CommandCondInfo build();
- }
-
/**
* Variable name the condition is stored under.
*/
@@ -53,4 +43,14 @@ public interface Builder {
*/
public abstract CodeBlock getConstruction();
+ @AutoValue.Builder
+ public interface Builder {
+
+ Builder condVariable(String variable);
+
+ Builder construction(CodeBlock construction);
+
+ CommandCondInfo build();
+ }
+
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandInfo.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandInfo.java
index c0aed66..d90b8bc 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandInfo.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandInfo.java
@@ -22,14 +22,17 @@
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
-import javax.annotation.Nullable;
-import javax.lang.model.element.ExecutableElement;
import java.util.Collection;
import java.util.Optional;
+import javax.annotation.Nullable;
+import javax.lang.model.element.ExecutableElement;
@AutoValue
public abstract class CommandInfo {
+ CommandInfo() {
+ }
+
public static Builder builder() {
Builder builder = new AutoValue_CommandInfo.Builder();
builder.footer(null);
@@ -37,6 +40,24 @@ public static Builder builder() {
return builder;
}
+ public abstract ExecutableElement getCommandMethod();
+
+ public abstract String getName();
+
+ public abstract String getGeneratedName();
+
+ public abstract ImmutableList getAliases();
+
+ public abstract String getDescription();
+
+ public abstract Optional getFooter();
+
+ public abstract ImmutableList getParams();
+
+ public abstract Optional getCondition();
+
+ public abstract Builder toBuilder();
+
@AutoValue.Builder
public interface Builder {
@@ -59,25 +80,4 @@ public interface Builder {
CommandInfo build();
}
- CommandInfo() {
- }
-
- public abstract ExecutableElement getCommandMethod();
-
- public abstract String getName();
-
- public abstract String getGeneratedName();
-
- public abstract ImmutableList getAliases();
-
- public abstract String getDescription();
-
- public abstract Optional getFooter();
-
- public abstract ImmutableList getParams();
-
- public abstract Optional getCondition();
-
- public abstract Builder toBuilder();
-
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandParamInfo.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandParamInfo.java
index b48721a..07fb7cd 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandParamInfo.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/CommandParamInfo.java
@@ -20,8 +20,8 @@
package org.enginehub.piston.gen.value;
import com.google.auto.value.AutoValue;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.TypeName;
import org.enginehub.piston.CommandParameters;
import javax.annotation.Nullable;
@@ -37,20 +37,6 @@ public static Builder builder() {
return new AutoValue_CommandParamInfo.Builder();
}
- @AutoValue.Builder
- public interface Builder {
-
- Builder name(@Nullable String name);
-
- Builder type(@Nullable TypeName type);
-
- Builder construction(@Nullable CodeBlock construction);
-
- Builder extractSpec(ExtractSpec extraction);
-
- CommandParamInfo build();
- }
-
/**
* Variable name, if used to store data.
*
@@ -78,4 +64,18 @@ public interface Builder {
public abstract Builder toBuilder();
+ @AutoValue.Builder
+ public interface Builder {
+
+ Builder name(@Nullable String name);
+
+ Builder type(@Nullable TypeName type);
+
+ Builder construction(@Nullable CodeBlock construction);
+
+ Builder extractSpec(ExtractSpec extraction);
+
+ CommandParamInfo build();
+ }
+
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/ExtractSpec.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/ExtractSpec.java
index 38af778..b74f3fb 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/ExtractSpec.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/ExtractSpec.java
@@ -21,11 +21,11 @@
import com.google.auto.value.AutoValue;
import com.google.auto.value.extension.memoized.Memoized;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.TypeName;
-import javax.annotation.Nullable;
import java.util.Objects;
+import javax.annotation.Nullable;
/**
* Specification for extracting a value.
@@ -33,34 +33,10 @@
@AutoValue
public abstract class ExtractSpec {
- @FunctionalInterface
- public interface ExtractMethodBody {
-
- /**
- * Generate extraction code, given that the parameter's part is stored in the given field.
- *
- * {@code partFieldName} will be {@code null} if there is no field.
- */
- CodeBlock generate(@Nullable String partFieldName);
-
- }
-
public static Builder builder() {
return new AutoValue_ExtractSpec.Builder();
}
- @AutoValue.Builder
- public interface Builder {
-
- Builder name(String name);
-
- Builder type(TypeName type);
-
- Builder extractMethodBody(ExtractMethodBody body);
-
- ExtractSpec build();
- }
-
/**
* Name for the extracted value.
*/
@@ -91,10 +67,9 @@ public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
- if (!(obj instanceof ExtractSpec)) {
+ if (!(obj instanceof ExtractSpec spec)) {
return false;
}
- ExtractSpec spec = (ExtractSpec) obj;
boolean fastChecks = Objects.equals(getName(), spec.getName())
&& Objects.equals(getType(), spec.getType());
if (!fastChecks) {
@@ -109,4 +84,28 @@ public final boolean equals(Object obj) {
public final int hashCode() {
return Objects.hash(getName(), getType(), getGeneratedMethodBody());
}
+
+ @FunctionalInterface
+ public interface ExtractMethodBody {
+
+ /**
+ * Generate extraction code, given that the parameter's part is stored in the given field.
+ *
+ * {@code partFieldName} will be {@code null} if there is no field.
+ */
+ CodeBlock generate(@Nullable String partFieldName);
+
+ }
+
+ @AutoValue.Builder
+ public interface Builder {
+
+ Builder name(String name);
+
+ Builder type(TypeName type);
+
+ Builder extractMethodBody(ExtractMethodBody body);
+
+ ExtractSpec build();
+ }
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/KeyInfo.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/KeyInfo.java
index 3fe98dd..0eb8b23 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/KeyInfo.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/KeyInfo.java
@@ -21,35 +21,35 @@
import com.google.auto.value.AutoValue;
import com.google.common.reflect.TypeToken;
-import com.squareup.javapoet.AnnotationSpec;
-import com.squareup.javapoet.ClassName;
-import com.squareup.javapoet.CodeBlock;
-import com.squareup.javapoet.MethodSpec;
-import com.squareup.javapoet.ParameterSpec;
-import com.squareup.javapoet.ParameterizedTypeName;
-import com.squareup.javapoet.TypeName;
-import com.squareup.javapoet.TypeSpec;
+import com.palantir.javapoet.AnnotationSpec;
+import com.palantir.javapoet.ClassName;
+import com.palantir.javapoet.CodeBlock;
+import com.palantir.javapoet.MethodSpec;
+import com.palantir.javapoet.ParameterSpec;
+import com.palantir.javapoet.ParameterizedTypeName;
+import com.palantir.javapoet.TypeName;
+import com.palantir.javapoet.TypeSpec;
import org.enginehub.piston.gen.util.CodeBlockUtil;
import org.enginehub.piston.gen.util.SafeName;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.util.CaseHelper;
-import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
+import javax.annotation.Nullable;
@AutoValue
public abstract class KeyInfo {
- public static KeyInfo of(TypeName typeName, @Nullable AnnotationSpec annotationSpec) {
- return new AutoValue_KeyInfo(typeName, annotationSpec);
+ KeyInfo() {
}
- KeyInfo() {
+ public static KeyInfo of(TypeName typeName, @Nullable AnnotationSpec annotationSpec) {
+ return new AutoValue_KeyInfo(typeName, annotationSpec);
}
public abstract TypeName typeName();
@@ -63,19 +63,14 @@ public final TypeName wrappedTypeName(Class> wrapper) {
public final String getVariableName() {
AnnotationSpec spec = annotationSpec();
- return SafeName.getNameAsIdentifier(typeName()) +
- "_" +
- (spec == null
- ? ""
- : getSpecName(spec) + "_") +
- "Key";
+ return SafeName.getNameAsIdentifier(typeName()) + "_" + (spec == null ? "" : getSpecName(spec) + "_") + "Key";
}
private String getSpecName(AnnotationSpec spec) {
StringBuilder name = new StringBuilder();
- name.append(SafeName.getNameAsIdentifier(spec.type));
+ name.append(SafeName.getNameAsIdentifier(spec.type()));
for (Iterator>> iterator
- = spec.members.entrySet().iterator();
+ = spec.members().entrySet().iterator();
iterator.hasNext(); ) {
Map.Entry> entry = iterator.next();
if (!entry.getKey().equals("value")) {
@@ -122,8 +117,8 @@ private CodeBlock getAnnotationArgumentCode() {
if (spec == null) {
return null;
}
- if (spec.members.isEmpty()) {
- return CodeBlock.of("$T.class", spec.type);
+ if (spec.members().isEmpty()) {
+ return CodeBlock.of("$T.class", spec.type());
}
return runtimeAnnotationExtractor(spec);
}
@@ -131,7 +126,8 @@ private CodeBlock getAnnotationArgumentCode() {
private CodeBlock runtimeAnnotationExtractor(AnnotationSpec annotationSpec) {
// _technically_ the spec can only be applied to parameters
// so we'll whip up a fake inner method with the annotation
- // and at runtime, reflect out the instance
+ // and at runtime, reflect out the instance retrieve this method
+ // and get its first parameter's first annotation (again, only one)
TypeSpec annoExtractor = TypeSpec.anonymousClassBuilder("")
// `a` = "annotation", extracts the annotation from its own parameter `ah`
.addMethod(MethodSpec.methodBuilder("a")
@@ -141,17 +137,11 @@ private CodeBlock runtimeAnnotationExtractor(AnnotationSpec annotationSpec) {
.addAnnotation(annotationSpec)
.build())
.beginControlFlow("try")
- .addStatement(
- // from this class
- "return getClass()" +
- // retrieve this method
- ".getDeclaredMethod(\"a\", $T.class)" +
- // and get its first parameter's first annotation (again, only one)
- ".getParameterAnnotations()[0][0]", Object.class)
+ // from this class
+ .addStatement("return getClass().getDeclaredMethod(\"a\", $T.class).getParameterAnnotations()[0][0]", Object.class)
.nextControlFlow("catch ($T e)", NoSuchMethodException.class)
.addStatement("throw new $T(e)", RuntimeException.class)
- .endControlFlow()
- .build())
+ .endControlFlow().build())
.build();
// call the method with a null parameter, since it doesn't really matter
return CodeBlock.of("$L.a(null)", annoExtractor);
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RegistrationInfo.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RegistrationInfo.java
index 3f3b40b..1d3d71b 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RegistrationInfo.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RegistrationInfo.java
@@ -22,16 +22,19 @@
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
-import com.squareup.javapoet.ClassName;
+import com.palantir.javapoet.ClassName;
+import java.util.Collection;
import javax.annotation.Nullable;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
-import java.util.Collection;
@AutoValue
public abstract class RegistrationInfo {
+ RegistrationInfo() {
+ }
+
public static Builder builder() {
Builder builder = new AutoValue_RegistrationInfo.Builder();
builder.injectedVariablesBuilder();
@@ -40,6 +43,23 @@ public static Builder builder() {
return builder;
}
+ public abstract String getName();
+
+ public abstract ClassName getTargetClassName();
+
+ @Nullable
+ public abstract Modifier getClassVisibility();
+
+ public abstract ImmutableList getCommands();
+
+ public abstract ImmutableList getInjectedVariables();
+
+ public abstract ImmutableList getDeclaredFields();
+
+ public abstract ImmutableSet getKeyTypes();
+
+ public abstract ImmutableSet getSuperTypes();
+
@AutoValue.Builder
public interface Builder {
@@ -83,24 +103,4 @@ default Builder addSuperType(TypeElement superType) {
}
- RegistrationInfo() {
- }
-
- public abstract String getName();
-
- public abstract ClassName getTargetClassName();
-
- @Nullable
- public abstract Modifier getClassVisibility();
-
- public abstract ImmutableList getCommands();
-
- public abstract ImmutableList getInjectedVariables();
-
- public abstract ImmutableList getDeclaredFields();
-
- public abstract ImmutableSet getKeyTypes();
-
- public abstract ImmutableSet getSuperTypes();
-
}
diff --git a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RequiredVariable.java b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RequiredVariable.java
index 1544480..1e176b0 100644
--- a/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RequiredVariable.java
+++ b/core-ap/processor/src/main/java/org/enginehub/piston/gen/value/RequiredVariable.java
@@ -21,20 +21,34 @@
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
-import com.squareup.javapoet.AnnotationSpec;
-import com.squareup.javapoet.TypeName;
+import com.palantir.javapoet.AnnotationSpec;
+import com.palantir.javapoet.TypeName;
import java.util.Collection;
@AutoValue
public abstract class RequiredVariable {
+ RequiredVariable() {
+ }
+
public static Builder builder() {
return new AutoValue_RequiredVariable.Builder()
.inherited(false)
.annotations(ImmutableList.of());
}
+ /**
+ * Check if this variable inherited from another interface.
+ */
+ public abstract boolean isInherited();
+
+ public abstract TypeName getType();
+
+ public abstract String getName();
+
+ public abstract ImmutableList getAnnotations();
+
@AutoValue.Builder
public interface Builder {
@@ -50,19 +64,5 @@ public interface Builder {
}
- RequiredVariable() {
- }
-
- /**
- * Is this variable inherited from another interface?
- */
- public abstract boolean isInherited();
-
- public abstract TypeName getType();
-
- public abstract String getName();
-
- public abstract ImmutableList getAnnotations();
-
}
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/BasicCommandTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/BasicCommandTest.kt
index 3b13ae5..1fce034 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/BasicCommandTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/BasicCommandTest.kt
@@ -19,14 +19,7 @@
package org.enginehub.piston
-import org.enginehub.piston.commands.NoArgCommand
-import org.enginehub.piston.commands.NoArgCommandRegistration
-import org.enginehub.piston.commands.NoArgWithInjectedCommand
-import org.enginehub.piston.commands.NoArgWithInjectedCommandRegistration
-import org.enginehub.piston.commands.SingleArgCommand
-import org.enginehub.piston.commands.SingleArgCommandRegistration
-import org.enginehub.piston.commands.SingleOptionalArgCommand
-import org.enginehub.piston.commands.SingleOptionalArgCommandRegistration
+import org.enginehub.piston.commands.*
import org.enginehub.piston.exception.UsageException
import org.enginehub.piston.inject.InjectedValueAccess
import org.enginehub.piston.inject.Key
@@ -60,9 +53,13 @@ class BasicCommandTest {
installCommands(ci, NoArgWithInjectedCommandRegistration.builder())
}
- manager.execute(MapBackedValueStore.create(mapOf(
- Key.of(String::class.java) to ValueProvider.constant(injected)
- )), listOf("no-arg-injected"))
+ manager.execute(
+ MapBackedValueStore.create(
+ mapOf(
+ Key.of(String::class.java) to ValueProvider.constant(injected)
+ )
+ ), listOf("no-arg-injected")
+ )
verify(ci).noArg(injected)
}
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/MoreAssertions.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/MoreAssertions.kt
index 8a6e628..b1ab0cb 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/MoreAssertions.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/MoreAssertions.kt
@@ -31,8 +31,10 @@ private fun prefix(message: String?): String {
fun assertEqualUnordered(expected: Collection, actual: Collection, message: String? = null) {
assertNotNull(actual, message)
- assertEquals(expected.size, actual.size,
- prefix(message) + "Not of equal size: expected: $expected, actual: $actual")
+ assertEquals(
+ expected.size, actual.size,
+ prefix(message) + "Not of equal size: expected: $expected, actual: $actual"
+ )
val expectedSet = expected.toSet()
val actualSet = actual.toSet()
assertEquals(expectedSet, actualSet, message)
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/RegressionTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/RegressionTest.kt
index 5c11e4f..d1537e8 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/RegressionTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/RegressionTest.kt
@@ -33,10 +33,7 @@ import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
-import org.mockito.Mockito.mock
-import org.mockito.Mockito.times
-import org.mockito.Mockito.verify
-import org.mockito.Mockito.verifyNoInteractions
+import org.mockito.Mockito.*
@DisplayName("Regression tests")
class RegressionTest {
@@ -70,8 +67,10 @@ class RegressionTest {
val usageEx = assertThrows {
manager.execute(InjectedValueAccess.EMPTY, listOf("i9", "5.x", "f"))
}
- assertEquals("Invalid value for (For input string: \"5.x\")," +
- " acceptable values are any double", usageEx.message)
+ assertEquals(
+ "Invalid value for (For input string: \"5.x\")," +
+ " acceptable values are any double", usageEx.message
+ )
}
}
}
@@ -90,12 +89,12 @@ class RegressionTest {
defaultsTo(listOf(""))
}
val sub = manager.newCommand("subcommand")
- .action {
- action(it.valueOf(arg).asString())
- 1
- }
- .description(TextComponent.of("Sub-command"))
- .build()
+ .action {
+ action(it.valueOf(arg).asString())
+ 1
+ }
+ .description(TextComponent.of("Sub-command"))
+ .build()
cmd.run {
description(TextComponent.of("Issue 9 #2"))
// Optional arg prior to sub-command
@@ -136,9 +135,9 @@ class RegressionTest {
defaultsTo(listOf("default-value"))
}
val sub = manager.newCommand("vert")
- .action { SUB_ACTION }
- .description(TextComponent.of("Sub-command"))
- .build()
+ .action { SUB_ACTION }
+ .description(TextComponent.of("Sub-command"))
+ .build()
cmd.run {
action { ROOT_ACTION }
description(TextComponent.of("Issue 14"))
@@ -149,16 +148,16 @@ class RegressionTest {
}
assertEquals(
- SUB_ACTION,
- manager.execute(InjectedValueAccess.EMPTY, listOf("i14", "vert"))
+ SUB_ACTION,
+ manager.execute(InjectedValueAccess.EMPTY, listOf("i14", "vert"))
)
assertEquals(
- ROOT_ACTION,
- manager.execute(InjectedValueAccess.EMPTY, listOf("i14", "10"))
+ ROOT_ACTION,
+ manager.execute(InjectedValueAccess.EMPTY, listOf("i14", "10"))
)
assertEquals(
- ROOT_ACTION,
- manager.execute(InjectedValueAccess.EMPTY, listOf("i14", "10", "north"))
+ ROOT_ACTION,
+ manager.execute(InjectedValueAccess.EMPTY, listOf("i14", "10", "north"))
)
}
}
@@ -169,10 +168,10 @@ class RegressionTest {
withRegressionCommands { _, manager ->
manager.register("hello") { cmd ->
val sub = manager.newCommand("world")
- .action { SUB_ACTION }
- .aliases(setOf("there"))
- .description(TextComponent.of("Sub-command"))
- .build()
+ .action { SUB_ACTION }
+ .aliases(setOf("there"))
+ .description(TextComponent.of("Sub-command"))
+ .build()
cmd.run {
description(TextComponent.of("hello"))
addPart(subs(sub, required = true))
@@ -180,12 +179,12 @@ class RegressionTest {
}
assertEquals(
- SUB_ACTION,
- manager.execute(InjectedValueAccess.EMPTY, listOf("hello", "world"))
+ SUB_ACTION,
+ manager.execute(InjectedValueAccess.EMPTY, listOf("hello", "world"))
)
assertEquals(
- SUB_ACTION,
- manager.execute(InjectedValueAccess.EMPTY, listOf("hello", "there")) // general kenobi
+ SUB_ACTION,
+ manager.execute(InjectedValueAccess.EMPTY, listOf("hello", "there")) // general kenobi
)
}
}
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/TestSupport.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/TestSupport.kt
index 0ab6074..fa47eb8 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/TestSupport.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/TestSupport.kt
@@ -24,19 +24,16 @@ import com.google.common.collect.ImmutableSet
import net.kyori.text.TextComponent
import net.kyori.text.TranslatableComponent
import org.enginehub.piston.gen.CommandRegistration
-import org.enginehub.piston.part.ArgAcceptingCommandFlag
-import org.enginehub.piston.part.CommandArgument
-import org.enginehub.piston.part.CommandPart
-import org.enginehub.piston.part.CommandParts
-import org.enginehub.piston.part.NoArgCommandFlag
-import org.enginehub.piston.part.SubCommandPart
+import org.enginehub.piston.part.*
import org.mockito.Mockito.mock
import org.mockito.Mockito.verifyNoMoreInteractions
fun newManager(): CommandManager = DefaultCommandManagerService.getInstance().newCommandManager()
-fun CommandManager.installCommands(containerInstance: CI,
- containerRegistration: CommandRegistration) {
+fun CommandManager.installCommands(
+ containerInstance: CI,
+ containerRegistration: CommandRegistration
+) {
containerRegistration
.commandManager(this)
.containerInstance(containerInstance)
@@ -64,8 +61,10 @@ inline fun flag(name: Char, desc: String, block: NoArgCommandFlag.Builder.() ->
TextComponent.of(desc)
).also(block).build()
-inline fun argFlag(name: Char, desc: String, argName: String,
- block: ArgAcceptingCommandFlag.Builder.() -> Unit = {}): ArgAcceptingCommandFlag =
+inline fun argFlag(
+ name: Char, desc: String, argName: String,
+ block: ArgAcceptingCommandFlag.Builder.() -> Unit = {}
+): ArgAcceptingCommandFlag =
CommandParts.flag(
name,
TextComponent.of(desc)
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/BadGenerationTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/BadGenerationTest.kt
index 42bbdc0..ea0677d 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/BadGenerationTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/BadGenerationTest.kt
@@ -20,9 +20,9 @@
package org.enginehub.piston.gen
import com.google.testing.compile.CompilationSubject.assertThat
-import com.squareup.javapoet.AnnotationSpec
-import com.squareup.javapoet.MethodSpec
-import com.squareup.javapoet.ParameterSpec
+import com.palantir.javapoet.AnnotationSpec
+import com.palantir.javapoet.MethodSpec
+import com.palantir.javapoet.ParameterSpec
import org.enginehub.piston.CommandValue
import org.enginehub.piston.annotation.Command
import org.enginehub.piston.annotation.param.Arg
@@ -36,21 +36,25 @@ class BadGenerationTest {
@DisplayName("when given multiple @InjectAnnotations")
@Test
fun failMultipleInjectAnnotations() {
- val commands = commands("MultiInjectAnno", listOf(
- MethodSpec.methodBuilder("multiInject")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "multiInject")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- ParameterSpec.builder(CommandValue::class.java, "arg")
- .addAnnotation(InjectAlpha::class.java)
- .addAnnotation(InjectBeta::class.java)
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "MultiInjectAnno", listOf(
+ MethodSpec.methodBuilder("multiInject")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "multiInject")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ ParameterSpec.builder(CommandValue::class.java, "arg")
+ .addAnnotation(InjectAlpha::class.java)
+ .addAnnotation(InjectBeta::class.java)
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation).failed()
assertThat(compilation)
@@ -62,26 +66,34 @@ class BadGenerationTest {
@DisplayName("when given @Arg + @Switch")
@Test
fun failArgSwitchAnnotations() {
- val commands = commands("MultiArg", listOf(
- MethodSpec.methodBuilder("multiArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "multiArg")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- ParameterSpec.builder(CommandValue::class.java, "arg")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .addAnnotation(AnnotationSpec.builder(Switch::class.java)
- .addMember("name", "'f'")
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "MultiArg", listOf(
+ MethodSpec.methodBuilder("multiArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "multiArg")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ ParameterSpec.builder(CommandValue::class.java, "arg")
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .addAnnotation(
+ AnnotationSpec.builder(Switch::class.java)
+ .addMember("name", "'f'")
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation).failed()
assertThat(compilation)
@@ -93,27 +105,35 @@ class BadGenerationTest {
@DisplayName("when given @Switch + @ArgFlag")
@Test
fun failSwitchArgFlagAnnotations() {
- val commands = commands("MultiArg", listOf(
- MethodSpec.methodBuilder("multiArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "multiArg")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- ParameterSpec.builder(CommandValue::class.java, "arg")
- .addAnnotation(AnnotationSpec.builder(Switch::class.java)
- .addMember("name", "'f'")
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .addAnnotation(AnnotationSpec.builder(ArgFlag::class.java)
- .addMember("name", "'f'")
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "MultiArg", listOf(
+ MethodSpec.methodBuilder("multiArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "multiArg")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ ParameterSpec.builder(CommandValue::class.java, "arg")
+ .addAnnotation(
+ AnnotationSpec.builder(Switch::class.java)
+ .addMember("name", "'f'")
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .addAnnotation(
+ AnnotationSpec.builder(ArgFlag::class.java)
+ .addMember("name", "'f'")
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation).failed()
assertThat(compilation)
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/GoodGenerationTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/GoodGenerationTest.kt
index c729099..3ac0ef3 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/GoodGenerationTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/GoodGenerationTest.kt
@@ -21,13 +21,7 @@ package org.enginehub.piston.gen
import com.google.testing.compile.CompilationSubject.assertThat
import com.google.testing.compile.JavaFileObjects
-import com.squareup.javapoet.AnnotationSpec
-import com.squareup.javapoet.MethodSpec
-import com.squareup.javapoet.ParameterSpec
-import com.squareup.javapoet.ParameterizedTypeName
-import com.squareup.javapoet.TypeName
-import com.squareup.javapoet.TypeSpec
-import com.squareup.javapoet.WildcardTypeName
+import com.palantir.javapoet.*
import org.enginehub.piston.CommandParameters
import org.enginehub.piston.CommandValue
import org.enginehub.piston.annotation.Command
@@ -39,7 +33,6 @@ import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import java.util.concurrent.Callable
import java.util.function.Consumer
-import java.util.function.Function
import javax.lang.model.element.Modifier
@@ -49,40 +42,50 @@ class GenerationTest {
@DisplayName("some no argument commands")
@Test
fun generatesNoArg() {
- val commands = commands("NoArg", listOf(
- MethodSpec.methodBuilder("noArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "noArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addException(Exception::class.java)
- .build(),
- MethodSpec.methodBuilder("noArgFooter")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "noArgumentFooter")
- .addMember("desc", "\$S", "DESCRIPTION")
- .addMember("descFooter", "\$S", "DESC FOOTER")
- .build())
- .returns(Void.TYPE)
- .build(),
- MethodSpec.methodBuilder("noArgCondition")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "noArgumentCondition")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .addAnnotation(AlwaysTrueCondition::class.java)
- .returns(Void.TYPE)
- .build(),
- MethodSpec.methodBuilder("noArgStatic")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "noArgumentStatic")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .addModifiers(Modifier.STATIC)
- .returns(Void.TYPE)
- .build()
- ))
+ val commands = commands(
+ "NoArg", listOf(
+ MethodSpec.methodBuilder("noArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "noArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addException(Exception::class.java)
+ .build(),
+ MethodSpec.methodBuilder("noArgFooter")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "noArgumentFooter")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .addMember("descFooter", $$"$S", "DESC FOOTER")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .build(),
+ MethodSpec.methodBuilder("noArgCondition")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "noArgumentCondition")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .addAnnotation(AlwaysTrueCondition::class.java)
+ .returns(Void.TYPE)
+ .build(),
+ MethodSpec.methodBuilder("noArgStatic")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "noArgumentStatic")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .addModifiers(Modifier.STATIC)
+ .returns(Void.TYPE)
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation)
.succeededWithoutWarnings()
@@ -94,26 +97,32 @@ class GenerationTest {
@DisplayName("some no argument commands (with non-arg parameters)")
@Test
fun generatesNoArgWithNonArgParameters() {
- val commands = commands("NonArgParameters", listOf(
- MethodSpec.methodBuilder("nonArgCommandParameters")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "nonArgCommandParameters")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(CommandParameters::class.java, "params")
- .build(),
- MethodSpec.methodBuilder("nonArgInjected")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "nonArgInjected")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- className>().parametrize(className()), "injected"
- )
- .build()
- ))
+ val commands = commands(
+ "NonArgParameters", listOf(
+ MethodSpec.methodBuilder("nonArgCommandParameters")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "nonArgCommandParameters")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(CommandParameters::class.java, "params")
+ .build(),
+ MethodSpec.methodBuilder("nonArgInjected")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "nonArgInjected")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ className>().parametrize(className()), "injected"
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation)
.succeededWithoutWarnings()
@@ -125,22 +134,28 @@ class GenerationTest {
@DisplayName("a one argument (CommandValue) command")
@Test
fun generatesOneCommandValueArg() {
- val commands = commands("CommandValueArg", listOf(
- MethodSpec.methodBuilder("valueArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "valueArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- ParameterSpec.builder(CommandValue::class.java, "arg")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "CommandValueArg", listOf(
+ MethodSpec.methodBuilder("valueArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "valueArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ ParameterSpec.builder(CommandValue::class.java, "arg")
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation)
.succeededWithoutWarnings()
@@ -152,25 +167,33 @@ class GenerationTest {
@DisplayName("a one argument (wildcard) command")
@Test
fun generatesOneWildcardArg() {
- val commands = commands("WildcardArg", listOf(
- MethodSpec.methodBuilder("valueArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "wildcardArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- ParameterSpec.builder(ParameterizedTypeName.get(
- className>(),
- WildcardTypeName.subtypeOf(TypeName.OBJECT)
- ), "arg")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "WildcardArg", listOf(
+ MethodSpec.methodBuilder("valueArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "wildcardArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ ParameterSpec.builder(
+ ParameterizedTypeName.get(
+ className>(),
+ WildcardTypeName.subtypeOf(ClassName.OBJECT)
+ ), "arg"
+ )
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation)
.succeededWithoutWarnings()
@@ -182,39 +205,49 @@ class GenerationTest {
@DisplayName("a one argument (Collection) command")
@Test
fun generatesOneCollectionArg() {
- val commands = commands("CollectionArg", listOf(
- MethodSpec.methodBuilder("collectionArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "collectionArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- ParameterSpec.builder(
- className>().parametrize(className()), "arg"
- )
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .build(),
- // Validate Object not multi-compatible
- MethodSpec.methodBuilder("objectArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "objectArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addParameter(
- ParameterSpec.builder(Object::class.java, "arg")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "CollectionArg", listOf(
+ MethodSpec.methodBuilder("collectionArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "collectionArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ ParameterSpec.builder(
+ className>().parametrize(className()), "arg"
+ )
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .build(),
+ // Validate Object not multi-compatible
+ MethodSpec.methodBuilder("objectArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "objectArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addParameter(
+ ParameterSpec.builder(Any::class.java, "arg") // Changed from [Object] to [Any] per compiler warnings
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation)
.succeededWithoutWarnings()
@@ -226,92 +259,118 @@ class GenerationTest {
@DisplayName("a one or more argument (int) command")
@Test
fun generatesOneIntArg() {
- val commands = commands("IntArg", listOf(
- MethodSpec.methodBuilder("intArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "intArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.INT)
- .addParameter(
- ParameterSpec.builder(TypeName.INT, "arg")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .addStatement("return arg")
- .build(),
- MethodSpec.methodBuilder("annotatedIntArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "annotatedIntArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.VOID)
- .addParameter(
- ParameterSpec.builder(TypeName.INT, "arg")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .addAnnotation(AnnotationSpec.builder(InjectGamma::class.java)
- .addMember("value", "\$S", "something to match")
- .build())
- .build()
- )
- .build(),
- MethodSpec.methodBuilder("annotatedIntArg2")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "annotatedIntArgument2")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.VOID)
- .addParameter(
- ParameterSpec.builder(TypeName.INT, "delta")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .addAnnotation(AnnotationSpec.builder(InjectDelta::class.java)
- .addMember("qux", "45")
- .addMember("baz", "32")
- .addMember("thq", "{ 10, 99 }")
- .build())
- .build()
- )
- .build(),
- MethodSpec.methodBuilder("annotatedIntArg3")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "annotatedIntArgument3")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.VOID)
- .addParameter(
- ParameterSpec.builder(TypeName.INT, "alpha")
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .addAnnotation(InjectAlpha::class.java)
- .build()
- )
- .build(),
- MethodSpec.methodBuilder("variableIntArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "variableIntArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.VOID)
- .addParameter(
- ParameterSpec.builder(
- className>().parametrize(className()), "arg"
- )
- .addAnnotation(AnnotationSpec.builder(Arg::class.java)
- .addMember("name", "\$S", "args")
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .addMember("variable", "true")
- .build())
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "IntArg", listOf(
+ MethodSpec.methodBuilder("intArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "intArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.INT)
+ .addParameter(
+ ParameterSpec.builder(TypeName.INT, "arg")
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .addStatement("return arg")
+ .build(),
+ MethodSpec.methodBuilder("annotatedIntArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "annotatedIntArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.VOID)
+ .addParameter(
+ ParameterSpec.builder(TypeName.INT, "arg")
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .addAnnotation(
+ AnnotationSpec.builder(InjectGamma::class.java)
+ .addMember("value", $$"$S", "something to match")
+ .build()
+ )
+ .build()
+ )
+ .build(),
+ MethodSpec.methodBuilder("annotatedIntArg2")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "annotatedIntArgument2")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.VOID)
+ .addParameter(
+ ParameterSpec.builder(TypeName.INT, "delta")
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .addAnnotation(
+ AnnotationSpec.builder(InjectDelta::class.java)
+ .addMember("qux", "45")
+ .addMember("baz", "32")
+ .addMember("thq", "{ 10, 99 }")
+ .build()
+ )
+ .build()
+ )
+ .build(),
+ MethodSpec.methodBuilder("annotatedIntArg3")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "annotatedIntArgument3")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.VOID)
+ .addParameter(
+ ParameterSpec.builder(TypeName.INT, "alpha")
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .addAnnotation(InjectAlpha::class.java)
+ .build()
+ )
+ .build(),
+ MethodSpec.methodBuilder("variableIntArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "variableIntArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.VOID)
+ .addParameter(
+ ParameterSpec.builder(
+ className>().parametrize(className()), "arg"
+ )
+ .addAnnotation(
+ AnnotationSpec.builder(Arg::class.java)
+ .addMember("name", $$"$S", "args")
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .addMember("variable", "true")
+ .build()
+ )
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation)
.succeededWithoutWarnings()
@@ -323,56 +382,70 @@ class GenerationTest {
@DisplayName("various flag commands")
@Test
fun generatesFlags() {
- val commands = commands("Flags", listOf(
- MethodSpec.methodBuilder("booleanFlag")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "booleanFlag")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.VOID)
- .addParameter(
- ParameterSpec.builder(TypeName.BOOLEAN, "flag")
- .addAnnotation(AnnotationSpec.builder(Switch::class.java)
- .addMember("name", "'f'")
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .build())
- .build()
- )
- .build(),
- MethodSpec.methodBuilder("stringArgFlag")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "stringArgFlag")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.VOID)
- .addParameter(
- ParameterSpec.builder(String::class.java, "flag")
- .addAnnotation(AnnotationSpec.builder(ArgFlag::class.java)
- .addMember("name", "'f'")
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .addMember("def", "\$S", "DEFAULT")
- .build())
- .build()
- )
- .build(),
- MethodSpec.methodBuilder("stringArgFlagCustom")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "stringArgFlagCustom")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(TypeName.VOID)
- .addParameter(
- ParameterSpec.builder(String::class.java, "flag")
- .addAnnotation(AnnotationSpec.builder(ArgFlag::class.java)
- .addMember("name", "'f'")
- .addMember("argName", "\$S", "ARG NAME")
- .addMember("desc", "\$S", "ARG DESCRIPTION")
- .addMember("def", "\$S", "DEFAULT")
- .build())
- .build()
- )
- .build()
- ))
+ val commands = commands(
+ "Flags", listOf(
+ MethodSpec.methodBuilder("booleanFlag")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "booleanFlag")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.VOID)
+ .addParameter(
+ ParameterSpec.builder(TypeName.BOOLEAN, "flag")
+ .addAnnotation(
+ AnnotationSpec.builder(Switch::class.java)
+ .addMember("name", "'f'")
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .build()
+ )
+ .build()
+ )
+ .build(),
+ MethodSpec.methodBuilder("stringArgFlag")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "stringArgFlag")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.VOID)
+ .addParameter(
+ ParameterSpec.builder(String::class.java, "flag")
+ .addAnnotation(
+ AnnotationSpec.builder(ArgFlag::class.java)
+ .addMember("name", "'f'")
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .addMember("def", $$"$S", "DEFAULT")
+ .build()
+ )
+ .build()
+ )
+ .build(),
+ MethodSpec.methodBuilder("stringArgFlagCustom")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "stringArgFlagCustom")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(TypeName.VOID)
+ .addParameter(
+ ParameterSpec.builder(String::class.java, "flag")
+ .addAnnotation(
+ AnnotationSpec.builder(ArgFlag::class.java)
+ .addMember("name", "'f'")
+ .addMember("argName", $$"$S", "ARG NAME")
+ .addMember("desc", $$"$S", "ARG DESCRIPTION")
+ .addMember("def", $$"$S", "DEFAULT")
+ .build()
+ )
+ .build()
+ )
+ .build()
+ )
+ )
val compilation = compiler().compile(commands)
assertThat(compilation)
.succeededWithoutWarnings()
@@ -385,10 +458,14 @@ class GenerationTest {
@Test
fun generatesSuperTypes() {
val commands = TypeSpec.classBuilder("SuperType")
- .addAnnotation(AnnotationSpec.builder(className())
- .addMember("superTypes", "{ \$T.class, \$T.class }",
- className(), className())
- .build())
+ .addAnnotation(
+ AnnotationSpec.builder(className())
+ .addMember(
+ "superTypes", $$"{ $T.class, $T.class }",
+ className(), className()
+ )
+ .build()
+ )
.build()
.toFileInPackage()
val compilation = compiler().compile(commands)
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/NestedClassTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/NestedClassTest.kt
index cd2cba8..a909f4f 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/NestedClassTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/NestedClassTest.kt
@@ -21,34 +21,36 @@ package org.enginehub.piston.gen
import com.google.testing.compile.CompilationSubject.assertThat
import com.google.testing.compile.JavaFileObjects
-import com.squareup.javapoet.AnnotationSpec
-import com.squareup.javapoet.MethodSpec
-import com.squareup.javapoet.TypeSpec
+import com.palantir.javapoet.AnnotationSpec
+import com.palantir.javapoet.MethodSpec
+import com.palantir.javapoet.TypeSpec
import org.enginehub.piston.annotation.Command
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
-
@DisplayName("core-ap can generate from a nested class")
class NestedClassTest {
@DisplayName("a basic command class")
@Test
fun basicTest() {
- val nestedClass = commandsSpec("BasicNested", listOf(
- MethodSpec.methodBuilder("noArg")
- .addAnnotation(AnnotationSpec.builder(Command::class.java)
- .addMember("name", "\$S", "noArgument")
- .addMember("desc", "\$S", "DESCRIPTION")
- .build())
- .returns(Void.TYPE)
- .addException(Exception::class.java)
- .build()
- ))
+ val nestedClass = commandsSpec(
+ "BasicNested", listOf(
+ MethodSpec.methodBuilder("noArg")
+ .addAnnotation(
+ AnnotationSpec.builder(Command::class.java)
+ .addMember("name", $$"$S", "noArgument")
+ .addMember("desc", $$"$S", "DESCRIPTION")
+ .build()
+ )
+ .returns(Void.TYPE)
+ .addException(Exception::class.java)
+ .build()
+ )
+ )
val outerClass = TypeSpec.classBuilder("Outer")
.addType(nestedClass)
.build()
-
val compilation = compiler().compile(outerClass.toFileInPackage())
assertThat(compilation)
.succeededWithoutWarnings()
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/Utils.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/Utils.kt
index d714e62..c8c5234 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/Utils.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/Utils.kt
@@ -21,12 +21,7 @@ package org.enginehub.piston.gen
import com.google.testing.compile.Compiler
import com.google.testing.compile.JavaFileObjects
-import com.squareup.javapoet.ClassName
-import com.squareup.javapoet.JavaFile
-import com.squareup.javapoet.MethodSpec
-import com.squareup.javapoet.ParameterizedTypeName
-import com.squareup.javapoet.TypeName
-import com.squareup.javapoet.TypeSpec
+import com.palantir.javapoet.*
import org.enginehub.piston.annotation.CommandContainer
import javax.tools.JavaFileObject
@@ -48,11 +43,11 @@ fun commands(name: String, specs: List): JavaFileObject {
fun TypeSpec.toFileInPackage(pkg: String = PACKAGE): JavaFileObject {
val source = JavaFile.builder(pkg, this).build().toString()
return JavaFileObjects.forSourceString(
- "$pkg.$name", source
+ "$pkg.${name()}", source
)
}
-fun compiler() = Compiler.javac().withProcessors(CommandProcessor())!!
+fun compiler(): Compiler = Compiler.javac().withProcessors(CommandProcessor()) // Removed [!!] per compiler warnings
inline fun className(): ClassName = ClassName.get(T::class.java)
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/AnnoValueExtractionTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/AnnoValueExtractionTest.kt
index 9798a07..ef639da 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/AnnoValueExtractionTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/AnnoValueExtractionTest.kt
@@ -27,8 +27,8 @@ import com.google.common.collect.ImmutableSet
import com.google.common.collect.ImmutableSetMultimap
import com.google.testing.compile.Compilation
import com.google.testing.compile.CompilationSubject.assertThat
-import com.squareup.javapoet.AnnotationSpec
-import com.squareup.javapoet.TypeSpec
+import com.palantir.javapoet.AnnotationSpec
+import com.palantir.javapoet.TypeSpec
import org.enginehub.piston.gen.className
import org.enginehub.piston.gen.compiler
import org.enginehub.piston.gen.toFileInPackage
@@ -45,10 +45,12 @@ class AnnoValueExtractionTest {
private val value = "test-value"
private val value2 = "tester-value"
private val annoCode = TypeSpec.classBuilder("AnnoContainer")
- .addAnnotation(AnnotationSpec.builder(className())
- .addMember("value", "\$S", value)
- .addMember("many", "{ \$S, \$S }", value, value2)
- .build())
+ .addAnnotation(
+ AnnotationSpec.builder(className())
+ .addMember("value", $$"$S", value)
+ .addMember("many", $$"{ $S, $S }", value, value2)
+ .build()
+ )
.build()
.toFileInPackage()
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/TypeNameUtilTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/TypeNameUtilTest.kt
index 878f973..254d32b 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/TypeNameUtilTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/util/TypeNameUtilTest.kt
@@ -21,8 +21,8 @@ package org.enginehub.piston.gen.util
import com.google.common.primitives.Primitives
import com.google.common.truth.Truth
-import com.squareup.javapoet.ArrayTypeName
-import com.squareup.javapoet.TypeName
+import com.palantir.javapoet.ArrayTypeName
+import com.palantir.javapoet.TypeName
import org.enginehub.piston.gen.className
import org.enginehub.piston.gen.parametrize
import org.junit.jupiter.api.Assertions.assertEquals
@@ -91,23 +91,31 @@ class TypeNameUtilTest {
@DisplayName("can resolve first type argument from ParameterizedTypeName")
@Test
fun firstTypeArgFromParameterizedTypeName() {
- assertEquals(className(), TypeNameUtil.firstTypeArg(
- className>().parametrize(className())
- ))
+ assertEquals(
+ className(), TypeNameUtil.firstTypeArg(
+ className>().parametrize(className())
+ )
+ )
}
@DisplayName("resolves Object as first type argument if not parameterized")
@Test
fun firstTypeArgFromOtherTypeName() {
- assertEquals(className(), TypeNameUtil.firstTypeArg(
- className()
- ))
- assertEquals(className(), TypeNameUtil.firstTypeArg(
- TypeName.INT
- ))
- assertEquals(className(), TypeNameUtil.firstTypeArg(
- TypeName.VOID
- ))
+ assertEquals(
+ className(), TypeNameUtil.firstTypeArg(
+ className()
+ )
+ )
+ assertEquals(
+ className(), TypeNameUtil.firstTypeArg(
+ TypeName.INT
+ )
+ )
+ assertEquals(
+ className(), TypeNameUtil.firstTypeArg(
+ TypeName.VOID
+ )
+ )
}
}
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/value/ExtractSpecTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/value/ExtractSpecTest.kt
index d7bb24d..8625dd3 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/value/ExtractSpecTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/gen/value/ExtractSpecTest.kt
@@ -19,11 +19,9 @@
package org.enginehub.piston.gen.value
-import com.squareup.javapoet.CodeBlock
+import com.palantir.javapoet.CodeBlock
import org.enginehub.piston.gen.className
-import org.junit.jupiter.api.Assertions.assertEquals
-import org.junit.jupiter.api.Assertions.assertNotEquals
-import org.junit.jupiter.api.Assertions.assertNotSame
+import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
@@ -33,7 +31,7 @@ class ExtractSpecTest {
private val extractSpec = ExtractSpec.builder()
.name("foo")
.type(className())
- .extractMethodBody { name -> CodeBlock.of("\$S", "My name is $name") }
+ .extractMethodBody { name -> CodeBlock.of($$"$S", "My name is $name") }
.build()
@DisplayName("is equal to itself")
@@ -68,7 +66,7 @@ class ExtractSpecTest {
@Test
fun isNotEqualDifferentGenerator() {
val copy = extractSpec.toBuilder().extractMethodBody { name ->
- CodeBlock.of("\$S", "I'm a different $name")
+ CodeBlock.of($$"$S", "I'm a different $name")
}.build()
assertNotEquals(extractSpec, copy)
}
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/ManagerSuggestionTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/ManagerSuggestionTest.kt
index f6ef715..f3a57a4 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/ManagerSuggestionTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/ManagerSuggestionTest.kt
@@ -20,31 +20,24 @@
package org.enginehub.piston.suggestion
import net.kyori.text.TextComponent
-import org.enginehub.piston.Command
-import org.enginehub.piston.CommandManager
-import org.enginehub.piston.assertEqualUnordered
+import org.enginehub.piston.*
import org.enginehub.piston.inject.InjectedValueAccess
import org.enginehub.piston.inject.Key
-import org.enginehub.piston.installCommands
-import org.enginehub.piston.newManager
-import org.enginehub.piston.subs
-import org.enginehub.piston.withMockedContainer
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
-import kotlin.streams.toList
@DisplayName("The manager's suggestion provider")
class ManagerSuggestionTest {
private val suggestionMatrix = listOf(
- setOf("art", "buck", "chair", "axe", "barely", "carrots"),
- setOf("123", "244", "312", "100", "213", "333"),
- setOf("something", "anything", "really"),
- // attempt to trigger a bug where completions go too far:
- setOf("something_else", "anything_else", "really_not_it"),
- setOf("something_else_entirely", "anything_else_except_this", "really_off")
+ setOf("art", "buck", "chair", "axe", "barely", "carrots"),
+ setOf("123", "244", "312", "100", "213", "333"),
+ setOf("something", "anything", "really"),
+ // attempt to trigger a bug where completions go too far:
+ setOf("something_else", "anything_else", "really_not_it"),
+ setOf("something_else_entirely", "anything_else_except_this", "really_off")
)
private fun withSuggestionManager(block: (CommandManager) -> Unit) {
@@ -52,8 +45,10 @@ class ManagerSuggestionTest {
val manager = newManager().apply {
installCommands(it, SuggestingCommandRegistration.builder())
suggestionMatrix.forEachIndexed { index, set ->
- registerConverter(Key.of(String::class.java, suggest(index + 1)),
- SimpleSuggestingConverter(set.toList()))
+ registerConverter(
+ Key.of(String::class.java, suggest(index + 1)),
+ SimpleSuggestingConverter(set.toList())
+ )
}
register("notpermitted") { cmd ->
@@ -79,7 +74,8 @@ class ManagerSuggestionTest {
fun suggestsCommandOnEmpty() {
withSuggestionManager { manager ->
val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY, listOf(""))
- assertEqualUnordered(manager.allCommands.map { it.name }.filter { it != "notpermitted" }.toList(),
+ assertEqualUnordered(
+ manager.allCommands.map { it.name }.filter { it != "notpermitted" }.toList(),
actualSuggestions.map { it.suggestion })
assertTrue(actualSuggestions.all { it.replacedArgument == 0 }, "replacement not targeted at first argument")
}
@@ -99,7 +95,8 @@ class ManagerSuggestionTest {
assertTrue(actualSuggestions.map { it.suggestion }.any { it == "permitted" }) {
"`permitted` not contained in suggestions"
}
- assertEqualUnordered(manager.allCommands.map { it.name }.filter { it != "notpermitted" }.toList(),
+ assertEqualUnordered(
+ manager.allCommands.map { it.name }.filter { it != "notpermitted" }.toList(),
actualSuggestions.map { it.suggestion })
assertTrue(actualSuggestions.all { it.replacedArgument == 0 }, "replacement not targeted at first argument")
}
@@ -111,7 +108,10 @@ class ManagerSuggestionTest {
withSuggestionManager { manager ->
val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY, listOf("cmd"))
assertEqualUnordered(suggestionMatrix[0], actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 1 }, "replacement not targeted at second argument")
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 1 },
+ "replacement not targeted at second argument"
+ )
}
}
@@ -121,9 +121,12 @@ class ManagerSuggestionTest {
withSuggestionManager { manager ->
val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY, listOf("cmd", "a"))
assertEqualUnordered(
- suggestionMatrix[0].filter(byPrefix("a")),
- actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 1 }, "replacement not targeted at second argument")
+ suggestionMatrix[0].filter(byPrefix("a")),
+ actualSuggestions.map { it.suggestion })
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 1 },
+ "replacement not targeted at second argument"
+ )
}
}
@@ -131,10 +134,13 @@ class ManagerSuggestionTest {
@DisplayName("suggests second and third argument if command & first selected")
fun suggestsSecondAndThird() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("cmd", suggestionMatrix[0].first()))
- assertEqualUnordered(suggestionMatrix[1] + suggestionMatrix[2],
- actualSuggestions.map { it.suggestion })
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("cmd", suggestionMatrix[0].first())
+ )
+ assertEqualUnordered(
+ suggestionMatrix[1] + suggestionMatrix[2],
+ actualSuggestions.map { it.suggestion })
assertTrue(actualSuggestions.all { it.replacedArgument == 2 }, "replacement not targeted at third argument")
}
}
@@ -144,17 +150,29 @@ class ManagerSuggestionTest {
fun suggestsSubSecondAndThird() {
withSuggestionManager { manager ->
assertAll({
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("cmd", suggestionMatrix[0].first(), "1"))
- assertEqualUnordered((suggestionMatrix[1] + suggestionMatrix[2]).filter(byPrefix("1")),
- actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 2 }, "replacement not targeted at third argument")
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("cmd", suggestionMatrix[0].first(), "1")
+ )
+ assertEqualUnordered(
+ (suggestionMatrix[1] + suggestionMatrix[2]).filter(byPrefix("1")),
+ actualSuggestions.map { it.suggestion })
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 2 },
+ "replacement not targeted at third argument"
+ )
}, {
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("cmd", suggestionMatrix[0].first(), "someth"))
- assertEqualUnordered((suggestionMatrix[1] + suggestionMatrix[2]).filter(byPrefix("someth")),
- actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 2 }, "replacement not targeted at third argument")
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("cmd", suggestionMatrix[0].first(), "someth")
+ )
+ assertEqualUnordered(
+ (suggestionMatrix[1] + suggestionMatrix[2]).filter(byPrefix("someth")),
+ actualSuggestions.map { it.suggestion })
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 2 },
+ "replacement not targeted at third argument"
+ )
})
}
}
@@ -163,10 +181,15 @@ class ManagerSuggestionTest {
@DisplayName("suggests flags on `-` input")
fun suggestsFlag() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("flags", "-"))
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("flags", "-")
+ )
assertEqualUnordered(setOf("-1", "-2", "-3"), actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 1 }, "replacement not targeted at second argument")
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 1 },
+ "replacement not targeted at second argument"
+ )
}
}
@@ -174,10 +197,15 @@ class ManagerSuggestionTest {
@DisplayName("suggests only unused flags on `-1` input")
fun suggestsOnlyUnusedFlag() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("flags", "-1"))
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("flags", "-1")
+ )
assertEqualUnordered(setOf("-12", "-13"), actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 1 }, "replacement not targeted at second argument")
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 1 },
+ "replacement not targeted at second argument"
+ )
}
}
@@ -185,8 +213,10 @@ class ManagerSuggestionTest {
@DisplayName("suggests argument for argument flags")
fun suggestsArgumentForArgumentFlags() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("flags", "-3"))
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("flags", "-3")
+ )
assertEqualUnordered(suggestionMatrix[2], actualSuggestions.map { it.suggestion })
assertTrue(actualSuggestions.all { it.replacedArgument == 2 }, "replacement not targeted at third argument")
}
@@ -196,10 +226,13 @@ class ManagerSuggestionTest {
@DisplayName("suggests parts of arguments for argument flags")
fun suggestsSubArgumentForArgumentFlags() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("flags", "-3", "any"))
- assertEqualUnordered(suggestionMatrix[2].filter(byPrefix("any")),
- actualSuggestions.map { it.suggestion })
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("flags", "-3", "any")
+ )
+ assertEqualUnordered(
+ suggestionMatrix[2].filter(byPrefix("any")),
+ actualSuggestions.map { it.suggestion })
assertTrue(actualSuggestions.all { it.replacedArgument == 2 }, "replacement not targeted at third argument")
}
}
@@ -208,10 +241,15 @@ class ManagerSuggestionTest {
@DisplayName("suggests sub-commands")
fun suggestsSubCommands() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("sub"))
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("sub")
+ )
assertEqualUnordered(setOf("cmd", "flags"), actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 1 }, "replacement not targeted at second argument")
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 1 },
+ "replacement not targeted at second argument"
+ )
}
}
@@ -219,10 +257,15 @@ class ManagerSuggestionTest {
@DisplayName("suggests partial sub-commands")
fun suggestsSubSubCommands() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("sub", "c"))
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("sub", "c")
+ )
assertEqualUnordered(setOf("cmd"), actualSuggestions.map { it.suggestion })
- assertTrue(actualSuggestions.all { it.replacedArgument == 1 }, "replacement not targeted at second argument")
+ assertTrue(
+ actualSuggestions.all { it.replacedArgument == 1 },
+ "replacement not targeted at second argument"
+ )
}
}
@@ -230,8 +273,10 @@ class ManagerSuggestionTest {
@DisplayName("suggests sub-command's arguments")
fun suggestsSubCommandArguments() {
withSuggestionManager { manager ->
- val actualSuggestions = manager.getSuggestions(InjectedValueAccess.EMPTY,
- listOf("sub", "cmd"))
+ val actualSuggestions = manager.getSuggestions(
+ InjectedValueAccess.EMPTY,
+ listOf("sub", "cmd")
+ )
assertEqualUnordered(suggestionMatrix[0], actualSuggestions.map { it.suggestion })
assertTrue(actualSuggestions.all { it.replacedArgument == 2 }, "replacement not targeted at thrid argument")
}
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/SuggestingCommand.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/SuggestingCommand.kt
index e25082b..2e3561c 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/SuggestingCommand.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/suggestion/SuggestingCommand.kt
@@ -28,13 +28,17 @@ import org.enginehub.piston.annotation.param.Switch
@CommandContainer
interface SuggestingCommand {
@Command(name = "cmd", desc = "description")
- fun cmd(@[Arg(desc = "First argument") Suggest(1)] first: String,
- @[Arg(desc = "Optional second argument", def = [""]) Suggest(2)] second: String,
- @[Arg(desc = "Required third argument") Suggest(3)] third: String,
- @[Arg(desc = "Required fourth argument") Suggest(4)] fourth: String)
+ fun cmd(
+ @[Arg(desc = "First argument") Suggest(1)] first: String,
+ @[Arg(desc = "Optional second argument", def = [""]) Suggest(2)] second: String,
+ @[Arg(desc = "Required third argument") Suggest(3)] third: String,
+ @[Arg(desc = "Required fourth argument") Suggest(4)] fourth: String
+ )
@Command(name = "flags", desc = "flag test command")
- fun flags(@[Switch(name = '1', desc = "First flag")] first: Boolean,
- @[Switch(name = '2', desc = "Second flag")] second: Boolean,
- @[ArgFlag(name = '3', desc = "Argument-taking third flag") Suggest(3)] third: String)
+ fun flags(
+ @[Switch(name = '1', desc = "First flag")] first: Boolean,
+ @[Switch(name = '2', desc = "Second flag")] second: Boolean,
+ @[ArgFlag(name = '3', desc = "Argument-taking third flag") Suggest(3)] third: String
+ )
}
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/HelpGeneratorTest.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/HelpGeneratorTest.kt
index c2fd987..8a02097 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/HelpGeneratorTest.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/HelpGeneratorTest.kt
@@ -21,27 +21,11 @@ package org.enginehub.piston.util
import com.google.common.collect.ImmutableList
import net.kyori.text.TextComponent
-import org.enginehub.piston.TestCommandMetadata
-import org.enginehub.piston.TestCommandParameters
-import org.enginehub.piston.TestParseResult
-import org.enginehub.piston.arg
-import org.enginehub.piston.argFlag
-import org.enginehub.piston.bind
-import org.enginehub.piston.commands.NoArgCommand
-import org.enginehub.piston.commands.NoArgCommandRegistration
-import org.enginehub.piston.commands.SingleArgCommand
-import org.enginehub.piston.commands.SingleArgCommandRegistration
-import org.enginehub.piston.commands.SingleOptionalArgCommand
-import org.enginehub.piston.commands.SingleOptionalArgCommandRegistration
-import org.enginehub.piston.flag
-import org.enginehub.piston.installCommands
-import org.enginehub.piston.newManager
-import org.enginehub.piston.subs
-import org.enginehub.piston.withMockedContainer
+import org.enginehub.piston.*
+import org.enginehub.piston.commands.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
-import kotlin.streams.toList
@DisplayName("HelpGenerator")
class HelpGeneratorTest {
@@ -54,10 +38,12 @@ class HelpGeneratorTest {
}
val command = manager.allCommands.toList()
- assertEquals("""
+ assertEquals(
+ """
description
Usage: no-arg
- """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp))
+ """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp)
+ )
}
}
@@ -69,12 +55,14 @@ class HelpGeneratorTest {
}
val command = manager.allCommands.toList()
- assertEquals("""
+ assertEquals(
+ """
description
Usage: single-arg
Arguments:
: First argument
- """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp))
+ """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp)
+ )
}
}
@@ -86,53 +74,62 @@ class HelpGeneratorTest {
}
val command = manager.allCommands.toList()
- assertEquals("""
+ assertEquals(
+ """
description
Usage: single-arg-opt [piston.argument.first]
Arguments:
[piston.argument.first] (defaults to none): First argument
- """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp))
+ """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp)
+ )
}
}
@Test
fun singleArgOptionalNotNoneHelp() {
- val command = listOf(newManager().newCommand("single-arg-opt")
- .description(TextComponent.of("description"))
- .addParts(
- arg("piston.argument.first","First argument") {
- defaultsTo(ImmutableList.of("a", "b"))
- }
- )
- .build())
- assertEquals("""
+ val command = listOf(
+ newManager().newCommand("single-arg-opt")
+ .description(TextComponent.of("description"))
+ .addParts(
+ arg("piston.argument.first", "First argument") {
+ defaultsTo(ImmutableList.of("a", "b"))
+ }
+ )
+ .build()
+ )
+ assertEquals(
+ """
description
Usage: single-arg-opt [piston.argument.first]
Arguments:
[piston.argument.first] (defaults to [a, b]): First argument
- """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp))
+ """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp)
+ )
}
@Test
fun flagsHelp() {
- val command = listOf(newManager().newCommand("flags")
- .description(TextComponent.of("description"))
- .addParts(
- flag('f', "Flag"),
- argFlag('q', "Quibble", "qux"),
- argFlag('b', "Bizarre", "baz") {
- defaultsTo(ImmutableList.of("", "nonblank"))
- }
- )
- .build())
- assertEquals("""
+ val command = listOf(
+ newManager().newCommand("flags")
+ .description(TextComponent.of("description"))
+ .addParts(
+ flag('f', "Flag"),
+ argFlag('q', "Quibble", "qux"),
+ argFlag('b', "Bizarre", "baz") {
+ defaultsTo(ImmutableList.of("", "nonblank"))
+ }
+ )
+ .build())
+ assertEquals(
+ """
description
Usage: flags [-f] [-q ] [-b ]
Flags:
-f: Flag
-q: Quibble
-b (defaults to [nonblank]): Bizarre
- """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp))
+ """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(command).fullHelp)
+ )
}
@Test
@@ -146,38 +143,53 @@ class HelpGeneratorTest {
.description(TextComponent.of("description"))
.addParts(interArg, subCommands)
.build()
- assertEquals("""
+ assertEquals(
+ """
description
Usage: main
Arguments:
: inter-arg
- """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(listOf(command)).fullHelp))
- assertEquals("""
+ """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(listOf(command)).fullHelp)
+ )
+ assertEquals(
+ """
sub-description
Usage: main sub-command
- """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(listOf(command, subCommand)).fullHelp))
- assertEquals("main inter-value sub-command", TextHelper.reduceToText(HelpGenerator.create(
- TestParseResult(
- ImmutableList.of(command, subCommand),
- ImmutableList.of(
- interArg.bind("inter-value"),
- subCommands.bind("sub-command")
- ),
- TestCommandParameters()
+ """.trimIndent(), TextHelper.reduceToText(HelpGenerator.create(listOf(command, subCommand)).fullHelp)
+ )
+ assertEquals(
+ "main inter-value sub-command", TextHelper.reduceToText(
+ HelpGenerator.create(
+ TestParseResult(
+ ImmutableList.of(command, subCommand),
+ ImmutableList.of(
+ interArg.bind("inter-value"),
+ subCommands.bind("sub-command")
+ ),
+ TestCommandParameters()
+ )
+ ).fullName
)
- ).fullName))
- assertEquals("main-alias inter-value sub-command", TextHelper.reduceToText(HelpGenerator.create(
- TestParseResult(
- ImmutableList.of(command, subCommand),
- ImmutableList.of(
- interArg.bind("inter-value"),
- subCommands.bind("sub-command")
- ),
- TestCommandParameters(
- TestCommandMetadata("main-alias", ImmutableList.of("main-alias", "inter-value", "sub-command"))
- )
+ )
+ assertEquals(
+ "main-alias inter-value sub-command", TextHelper.reduceToText(
+ HelpGenerator.create(
+ TestParseResult(
+ ImmutableList.of(command, subCommand),
+ ImmutableList.of(
+ interArg.bind("inter-value"),
+ subCommands.bind("sub-command")
+ ),
+ TestCommandParameters(
+ TestCommandMetadata(
+ "main-alias",
+ ImmutableList.of("main-alias", "inter-value", "sub-command")
+ )
+ )
+ )
+ ).fullName
)
- ).fullName))
+ )
}
}
\ No newline at end of file
diff --git a/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/PreloadTypeNameExtension.kt b/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/PreloadTypeNameExtension.kt
index 57e6c3b..f4a6692 100644
--- a/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/PreloadTypeNameExtension.kt
+++ b/core-ap/processor/src/test/kotlin/org/enginehub/piston/util/PreloadTypeNameExtension.kt
@@ -20,7 +20,7 @@
package org.enginehub.piston.util
import com.google.auto.service.AutoService
-import com.squareup.javapoet.TypeName
+import com.palantir.javapoet.TypeName
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.Extension
import org.junit.jupiter.api.extension.ExtensionContext
@@ -38,8 +38,7 @@ class PreloadTypeNameExtension : Extension, BeforeAllCallback {
private val loadLock = ReentrantLock()
- override fun beforeAll(context: ExtensionContext?) = loadLock.withLock {
- TypeName.get(Object::class.java)
- Unit
+ override fun beforeAll(context: ExtensionContext): Unit = loadLock.withLock {
+ TypeName.get(Any::class.java) // Changed from [Object] to [Any] per compiler warnings
}
}
diff --git a/core-ap/processor/src/test/resources/logback.xml b/core-ap/processor/src/test/resources/logback.xml
index 6da048b..296caa1 100644
--- a/core-ap/processor/src/test/resources/logback.xml
+++ b/core-ap/processor/src/test/resources/logback.xml
@@ -18,13 +18,13 @@
-->
-
-
- [%thread/%level{5}][%logger{1}]: %msg%rEx%n
-
-
+
+
+ [%thread/%level{5}][%logger{1}]: %msg%rEx%n
+
+
-
-
-
+
+
+
\ No newline at end of file
diff --git a/core-ap/runtime/build.gradle.kts b/core-ap/runtime/build.gradle.kts
index 4bbfbec..bb9ef78 100644
--- a/core-ap/runtime/build.gradle.kts
+++ b/core-ap/runtime/build.gradle.kts
@@ -1,7 +1,7 @@
-applyCoreApConfig()
+plugins {
+ id("buildlogic.core-ap")
+}
dependencies {
"api"(project(":core"))
-
- "testImplementation"(Libs.mockito)
}
diff --git a/core-ap/runtime/src/main/java/org/enginehub/piston/gen/CommandCallListener.java b/core-ap/runtime/src/main/java/org/enginehub/piston/gen/CommandCallListener.java
index 92ee125..2d74db2 100644
--- a/core-ap/runtime/src/main/java/org/enginehub/piston/gen/CommandCallListener.java
+++ b/core-ap/runtime/src/main/java/org/enginehub/piston/gen/CommandCallListener.java
@@ -32,7 +32,7 @@ public interface CommandCallListener {
* Called before invoking the actual command method.
*
* @param commandMethod the method
- * @param parameters the full parameters for the command
+ * @param parameters the full parameters for the command
*/
default void beforeCall(Method commandMethod, CommandParameters parameters) {
}
@@ -42,7 +42,7 @@ default void beforeCall(Method commandMethod, CommandParameters parameters) {
* if it was successful.
*
* @param commandMethod the method
- * @param parameters the full parameters for the command
+ * @param parameters the full parameters for the command
*/
default void afterCall(Method commandMethod, CommandParameters parameters) {
}
@@ -52,8 +52,8 @@ default void afterCall(Method commandMethod, CommandParameters parameters) {
* if it threw an exception.
*
* @param commandMethod the method
- * @param error the exception thrown by the method
- * @param parameters the full parameters for the command
+ * @param error the exception thrown by the method
+ * @param parameters the full parameters for the command
*/
default void afterThrow(Method commandMethod, CommandParameters parameters, Throwable error) {
}
diff --git a/core-ap/runtime/src/main/java/org/enginehub/piston/internal/RegistrationUtil.java b/core-ap/runtime/src/main/java/org/enginehub/piston/internal/RegistrationUtil.java
index 3ff35e9..a9c0c49 100644
--- a/core-ap/runtime/src/main/java/org/enginehub/piston/internal/RegistrationUtil.java
+++ b/core-ap/runtime/src/main/java/org/enginehub/piston/internal/RegistrationUtil.java
@@ -32,6 +32,10 @@
*/
public class RegistrationUtil {
+ private RegistrationUtil() {
+ throw new RuntimeException();
+ }
+
public static T requireOptional(Key type, String name, Optional optional) {
return optional.orElseThrow(() ->
new IllegalStateException("No injected value for " + name + " (type " + type + ")")
@@ -71,8 +75,4 @@ public static void listenersAfterThrow(List listeners,
}
}
- private RegistrationUtil() {
- throw new RuntimeException();
- }
-
}
diff --git a/core-ap/runtime/src/test/java/org/enginehub/piston/util/RegistrationUtilTest.java b/core-ap/runtime/src/test/java/org/enginehub/piston/util/RegistrationUtilTest.java
index de29d12..767ec36 100644
--- a/core-ap/runtime/src/test/java/org/enginehub/piston/util/RegistrationUtilTest.java
+++ b/core-ap/runtime/src/test/java/org/enginehub/piston/util/RegistrationUtilTest.java
@@ -43,6 +43,19 @@
@DisplayName("RegistrationUtil")
public class RegistrationUtilTest {
+ private final Method fakeCommandMethod;
+ private final CommandParameters parameters = NoInputCommandParameters.builder()
+ .build();
+ private final CommandCallListener listener = mock(CommandCallListener.class);
+
+ {
+ try {
+ fakeCommandMethod = getClass().getDeclaredMethod("requireOptional");
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
@Test
void noConstruction() throws Exception {
Constructor constructor = RegistrationUtil.class.getDeclaredConstructor();
@@ -61,16 +74,6 @@ void requireOptional() {
assertTrue(ex.getMessage().contains(Key.of(String.class).toString()));
}
- private final Method fakeCommandMethod;
-
- {
- try {
- fakeCommandMethod = getClass().getDeclaredMethod("requireOptional");
- } catch (NoSuchMethodException e) {
- throw new IllegalStateException(e);
- }
- }
-
@Test
void getCommandMethod() {
assertEquals(fakeCommandMethod,
@@ -80,10 +83,6 @@ void getCommandMethod() {
assertTrue(ex.getMessage().contains("Missing command method"));
}
- private final CommandParameters parameters = NoInputCommandParameters.builder()
- .build();
- private final CommandCallListener listener = mock(CommandCallListener.class);
-
@Test
void listenersBeforeCall() {
RegistrationUtil.listenersBeforeCall(ImmutableList.of(listener), fakeCommandMethod, parameters);
@@ -91,6 +90,7 @@ void listenersBeforeCall() {
verify(listener).beforeCall(fakeCommandMethod, parameters);
verifyNoMoreInteractions(listener);
}
+
@Test
void listenersAfterCall() {
RegistrationUtil.listenersAfterCall(ImmutableList.of(listener), fakeCommandMethod, parameters);
@@ -98,6 +98,7 @@ void listenersAfterCall() {
verify(listener).afterCall(fakeCommandMethod, parameters);
verifyNoMoreInteractions(listener);
}
+
@Test
void listenersAfterThrow() {
Throwable ex = new RuntimeException();
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
index 3609940..cebcac3 100644
--- a/core/build.gradle.kts
+++ b/core/build.gradle.kts
@@ -1,11 +1,11 @@
-applyCommonConfig()
+plugins {
+ id("buildlogic.common")
+}
dependencies {
- "api"(Libs.guava)
- "api"(Libs.kyoriText)
- "api"(Libs.javaxAnnotations)
- "implementation"(Libs.kyoriTextPlain)
- "compileOnly"(Libs.autoValueAnnotations)
- "annotationProcessor"(Libs.autoValueProcessor)
- "testImplementation"(Libs.mockito)
+ "api"(libs.guava)
+ "api"(libs.kyoriText.api)
+ "implementation"(libs.kyoriText.serializer.plain)
+ "compileOnly"(libs.autoValue.annotations)
+ "annotationProcessor"(libs.autoValue)
}
diff --git a/core/src/main/java/org/enginehub/piston/ArgBinding.java b/core/src/main/java/org/enginehub/piston/ArgBinding.java
index f156cbd..5153d0c 100644
--- a/core/src/main/java/org/enginehub/piston/ArgBinding.java
+++ b/core/src/main/java/org/enginehub/piston/ArgBinding.java
@@ -20,7 +20,6 @@
package org.enginehub.piston;
import com.google.common.collect.ImmutableSet;
-import org.enginehub.piston.converter.SuccessfulConversion;
import org.enginehub.piston.part.CommandPart;
public interface ArgBinding {
@@ -31,7 +30,7 @@ public interface ArgBinding {
String getInput();
/**
- * Did we match the given part exactly?
+ * Check if we match the given part exactly.
*
* @param part the part, must be contained in the parts returned by {@link #getParts()}
* @since 0.5.8
diff --git a/core/src/main/java/org/enginehub/piston/Command.java b/core/src/main/java/org/enginehub/piston/Command.java
index 3bbad75..14973ad 100644
--- a/core/src/main/java/org/enginehub/piston/Command.java
+++ b/core/src/main/java/org/enginehub/piston/Command.java
@@ -26,9 +26,9 @@
import org.enginehub.piston.suggestion.SuggestionProvider;
import org.enginehub.piston.util.HelpGenerator;
-import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Optional;
+import javax.annotation.Nullable;
/**
* Represents a command. Commands can be modified using {@code with/add} functions,
@@ -41,6 +41,32 @@
*/
public interface Command {
+ String getName();
+
+ ImmutableList getAliases();
+
+ Component getDescription();
+
+ Optional getFooter();
+
+ ImmutableList getParts();
+
+ Condition getCondition();
+
+ Action getAction();
+
+ SuggestionProvider getSuggester();
+
+ Builder toBuilder();
+
+ default Component getUsage() {
+ return HelpGenerator.create(ImmutableList.of(this)).getUsage();
+ }
+
+ default Component getFullHelp() {
+ return HelpGenerator.create(ImmutableList.of(this)).getFullHelp();
+ }
+
/**
* Represents what a command does. An action usually does one or more things,
* and those should be counted and returned for user feedback.
@@ -101,7 +127,7 @@ default Condition not() {
* Retrieve this condition as a more specific type, if possible.
*
* @param type the class to cast to
- * @param the type of the output
+ * @param the type of the output
* @return this as {@code T}, if possible
*/
default Optional as(Class type) {
@@ -144,30 +170,4 @@ interface Builder {
}
- String getName();
-
- ImmutableList getAliases();
-
- Component getDescription();
-
- Optional getFooter();
-
- ImmutableList getParts();
-
- Condition getCondition();
-
- Action getAction();
-
- SuggestionProvider getSuggester();
-
- Builder toBuilder();
-
- default Component getUsage() {
- return HelpGenerator.create(ImmutableList.of(this)).getUsage();
- }
-
- default Component getFullHelp() {
- return HelpGenerator.create(ImmutableList.of(this)).getFullHelp();
- }
-
}
diff --git a/core/src/main/java/org/enginehub/piston/CommandManager.java b/core/src/main/java/org/enginehub/piston/CommandManager.java
index 9a86f4b..09eed42 100644
--- a/core/src/main/java/org/enginehub/piston/CommandManager.java
+++ b/core/src/main/java/org/enginehub/piston/CommandManager.java
@@ -60,7 +60,7 @@ public interface CommandManager extends ArgumentConverterStore {
/**
* Register a command that initially has the given name, and then is configured by a function.
*
- * @param name the name of the command
+ * @param name the name of the command
* @param registrationProcess a function that will build the command
*/
default void register(String name, Consumer registrationProcess) {
@@ -100,8 +100,7 @@ default boolean containsCommand(String name) {
* Includes aliases.
*
* @param name the name to check
- * @return {@link Optional#of(Object)} the command if registered,
- * otherwise {@link Optional#empty()}
+ * @return {@link Optional#of(Object)} the command if registered, otherwise {@link Optional#empty()}
*/
Optional getCommand(String name);
@@ -110,7 +109,7 @@ default boolean containsCommand(String name) {
* entire command line, so that partial parsing may occur.
*
* @param context the injected value context
- * @param args the command line to suggest into
+ * @param args the command line to suggest into
* @return the suggestions
*/
ImmutableSet getSuggestions(InjectedValueAccess context, List args);
@@ -133,7 +132,7 @@ default boolean containsCommand(String name) {
*
*
* @param context the injected value context
- * @param args the arguments to include
+ * @param args the arguments to include
* @return the parsing output
*/
CommandParseResult parse(InjectedValueAccess context, List args);
@@ -147,7 +146,7 @@ default boolean containsCommand(String name) {
*
*
* @param context the injected value context
- * @param args the arguments to include
+ * @param args the arguments to include
* @return the count from the executed command
*/
default int execute(InjectedValueAccess context, List args) {
diff --git a/core/src/main/java/org/enginehub/piston/DefaultCommandManagerService.java b/core/src/main/java/org/enginehub/piston/DefaultCommandManagerService.java
index 0ec9e7e..5774168 100644
--- a/core/src/main/java/org/enginehub/piston/DefaultCommandManagerService.java
+++ b/core/src/main/java/org/enginehub/piston/DefaultCommandManagerService.java
@@ -19,10 +19,10 @@
package org.enginehub.piston;
-import javax.annotation.Nullable;
import java.util.ServiceLoader;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Streams.stream;
@@ -39,6 +39,14 @@
public class DefaultCommandManagerService implements CommandManagerService {
private static final DefaultCommandManagerService INSTANCE = new DefaultCommandManagerService(getDefaultService());
+ private final Lock sealLock = new ReentrantLock();
+ private CommandManagerService defaultService;
+ @Nullable
+ private CommandManagerService sealedDefaultService;
+
+ private DefaultCommandManagerService(CommandManagerService defaultService) {
+ this.defaultService = defaultService;
+ }
public static DefaultCommandManagerService getInstance() {
return INSTANCE;
@@ -54,13 +62,14 @@ private static CommandManagerService getDefaultService() {
.orElseThrow(() -> new IllegalStateException("No default service available."));
}
- private final Lock sealLock = new ReentrantLock();
- private CommandManagerService defaultService;
- @Nullable
- private CommandManagerService sealedDefaultService;
-
- private DefaultCommandManagerService(CommandManagerService defaultService) {
- this.defaultService = defaultService;
+ public void setDefaultService(CommandManagerService defaultService) {
+ sealLock.lock();
+ try {
+ checkState(sealedDefaultService == null, "Piston default service is sealed");
+ this.defaultService = defaultService;
+ } finally {
+ sealLock.unlock();
+ }
}
private CommandManagerService sealDelegate() {
@@ -82,16 +91,6 @@ private CommandManagerService sealDelegate() {
return sealedDefaultService;
}
- public void setDefaultService(CommandManagerService defaultService) {
- sealLock.lock();
- try {
- checkState(sealedDefaultService == null, "Piston default service is sealed");
- this.defaultService = defaultService;
- } finally {
- sealLock.unlock();
- }
- }
-
@Override
public String id() {
return sealDelegate().id();
diff --git a/core/src/main/java/org/enginehub/piston/NoInputCommandParameters.java b/core/src/main/java/org/enginehub/piston/NoInputCommandParameters.java
index 4096517..3d1260c 100644
--- a/core/src/main/java/org/enginehub/piston/NoInputCommandParameters.java
+++ b/core/src/main/java/org/enginehub/piston/NoInputCommandParameters.java
@@ -26,9 +26,9 @@
import org.enginehub.piston.part.ArgAcceptingCommandPart;
import org.enginehub.piston.part.CommandPart;
-import javax.annotation.Nullable;
import java.util.NoSuchElementException;
import java.util.Optional;
+import javax.annotation.Nullable;
/**
* An implementation of {@link CommandParameters} for situations where it is needed,
@@ -37,27 +37,15 @@
@AutoValue
public abstract class NoInputCommandParameters implements CommandParameters {
+ NoInputCommandParameters() {
+ }
+
public static Builder builder() {
return new AutoValue_NoInputCommandParameters.Builder()
.injectedValues(InjectedValueAccess.EMPTY)
.converters(ArgumentConverterAccess.EMPTY);
}
- @AutoValue.Builder
- public interface Builder {
-
- Builder injectedValues(InjectedValueAccess values);
-
- Builder metadata(@Nullable CommandMetadata metadata);
-
- Builder converters(ArgumentConverterAccess access);
-
- NoInputCommandParameters build();
- }
-
- NoInputCommandParameters() {
- }
-
abstract InjectedValueAccess injectedValues();
@Nullable
@@ -91,4 +79,16 @@ public Optional injectedValue(Key key, InjectedValueAccess context) {
return injectedValues().injectedValue(key, context);
}
+ @AutoValue.Builder
+ public interface Builder {
+
+ Builder injectedValues(InjectedValueAccess values);
+
+ Builder metadata(@Nullable CommandMetadata metadata);
+
+ Builder converters(ArgumentConverterAccess access);
+
+ NoInputCommandParameters build();
+ }
+
}
diff --git a/core/src/main/java/org/enginehub/piston/config/ColorConfig.java b/core/src/main/java/org/enginehub/piston/config/ColorConfig.java
index 6b33c0e..0c0f2d1 100644
--- a/core/src/main/java/org/enginehub/piston/config/ColorConfig.java
+++ b/core/src/main/java/org/enginehub/piston/config/ColorConfig.java
@@ -26,10 +26,10 @@
import net.kyori.text.format.Style;
import net.kyori.text.format.TextColor;
-import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
+import javax.annotation.Nullable;
/**
* Color configuration.
@@ -49,6 +49,10 @@ public class ColorConfig extends Config {
Style.Merge.DECORATIONS, Style.Merge.INSERTION, Style.Merge.EVENTS
);
+ private ColorConfig(String key, @Nullable TextColor color) {
+ super(key, color);
+ }
+
/**
* Color for text that modifies the main text.
*/
@@ -77,10 +81,6 @@ public static ColorConfig partWrapping() {
return PART_WRAPPING;
}
- private ColorConfig(String key, @Nullable TextColor color) {
- super(key, color);
- }
-
@Override
protected Config copyForDefault() {
return new ColorConfig(getKey(), getValue());
diff --git a/core/src/main/java/org/enginehub/piston/config/Config.java b/core/src/main/java/org/enginehub/piston/config/Config.java
index 65dd85f..6ed6ed5 100644
--- a/core/src/main/java/org/enginehub/piston/config/Config.java
+++ b/core/src/main/java/org/enginehub/piston/config/Config.java
@@ -23,12 +23,12 @@
import net.kyori.text.Component;
import net.kyori.text.TranslatableComponent;
-import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
+import javax.annotation.Nullable;
public abstract class Config {
@@ -53,8 +53,7 @@ public String getKey() {
return key;
}
- public @Nullable
- T getValue() {
+ public @Nullable T getValue() {
return value;
}
diff --git a/core/src/main/java/org/enginehub/piston/config/ConfigHolder.java b/core/src/main/java/org/enginehub/piston/config/ConfigHolder.java
index 85e0d00..5ebbff2 100644
--- a/core/src/main/java/org/enginehub/piston/config/ConfigHolder.java
+++ b/core/src/main/java/org/enginehub/piston/config/ConfigHolder.java
@@ -32,16 +32,16 @@ public class ConfigHolder {
TextConfig.commandPrefix();
}
- public static ConfigHolder create() {
- return new ConfigHolder(Config.defaultInstances);
- }
-
private final Map> configs = new HashMap<>();
private ConfigHolder(Map> configs) {
this.configs.putAll(configs);
}
+ public static ConfigHolder create() {
+ return new ConfigHolder(Config.defaultInstances);
+ }
+
public Map> getConfigs() {
return configs;
}
diff --git a/core/src/main/java/org/enginehub/piston/config/ConfigRenderer.java b/core/src/main/java/org/enginehub/piston/config/ConfigRenderer.java
index 11f4b7f..e50771a 100644
--- a/core/src/main/java/org/enginehub/piston/config/ConfigRenderer.java
+++ b/core/src/main/java/org/enginehub/piston/config/ConfigRenderer.java
@@ -34,6 +34,9 @@ public class ConfigRenderer implements ComponentRenderer {
private static final ConfigRenderer INSTANCE = new ConfigRenderer();
+ private ConfigRenderer() {
+ }
+
/**
* Get an instance of the renderer.
*/
@@ -41,15 +44,11 @@ public static ConfigRenderer getInstance() {
return INSTANCE;
}
- private ConfigRenderer() {
- }
-
@Override
public @NonNull Component render(@NonNull Component component, @NonNull ConfigHolder context) {
component = replaceSubcomponents(component, context);
- if (component instanceof TranslatableComponent) {
+ if (component instanceof TranslatableComponent tc) {
// check if replacing
- TranslatableComponent tc = (TranslatableComponent) component;
Config> config = context.getConfigs().get(tc.key());
if (config != null) {
component = config.apply(tc);
@@ -59,8 +58,7 @@ private ConfigRenderer() {
}
private Component replaceSubcomponents(Component component, ConfigHolder context) {
- if (component instanceof TranslatableComponent) {
- TranslatableComponent tc = (TranslatableComponent) component;
+ if (component instanceof TranslatableComponent tc) {
List originalArgs = tc.args();
List replacementArgs = renderList(originalArgs, context);
if (originalArgs != replacementArgs) {
diff --git a/core/src/main/java/org/enginehub/piston/config/TextConfig.java b/core/src/main/java/org/enginehub/piston/config/TextConfig.java
index 3aa77b0..2f8bfeb 100644
--- a/core/src/main/java/org/enginehub/piston/config/TextConfig.java
+++ b/core/src/main/java/org/enginehub/piston/config/TextConfig.java
@@ -35,6 +35,10 @@ public class TextConfig extends Config {
private static final TextConfig COMMAND_PREFIX = new TextConfig("piston.text.command.prefix");
+ private TextConfig(String key) {
+ super(key, "");
+ }
+
/**
* Output command prefix -- all commands will be output with this prefix before their name.
*/
@@ -46,10 +50,6 @@ public static Component commandPrefixValue() {
return commandPrefix().value();
}
- private TextConfig(String key) {
- super(key, "");
- }
-
@Override
protected Config copyForDefault() {
return new TextConfig(getKey());
diff --git a/core/src/main/java/org/enginehub/piston/converter/ArgumentConverterStore.java b/core/src/main/java/org/enginehub/piston/converter/ArgumentConverterStore.java
index 9673d54..cf0b4b7 100644
--- a/core/src/main/java/org/enginehub/piston/converter/ArgumentConverterStore.java
+++ b/core/src/main/java/org/enginehub/piston/converter/ArgumentConverterStore.java
@@ -29,9 +29,9 @@ public interface ArgumentConverterStore extends ArgumentConverterAccess {
/**
* Register a converter for a given key.
*
- * @param key the key to register the converter under
+ * @param key the key to register the converter under
* @param converter the converter to register
- * @param the type of value returned by the converter
+ * @param the type of value returned by the converter
*/
void registerConverter(Key key, ArgumentConverter converter);
diff --git a/core/src/main/java/org/enginehub/piston/converter/ArgumentConverters.java b/core/src/main/java/org/enginehub/piston/converter/ArgumentConverters.java
index a7777cc..3334bbf 100644
--- a/core/src/main/java/org/enginehub/piston/converter/ArgumentConverters.java
+++ b/core/src/main/java/org/enginehub/piston/converter/ArgumentConverters.java
@@ -47,6 +47,62 @@ public class ArgumentConverters {
private static final ArgumentConverter STRING_ARGUMENT_CONVERTER =
SimpleArgumentConverter.from((s, c) -> SuccessfulConversion.fromSingle(s), "any text");
+ private static final String CONVERTER_CONVERT = "convert";
+ private static final MethodType HANDLE_TO_CONVERTER = methodType(Converter.class, MethodHandle.class);
+ private static final MethodType CONVERTER_SIG = methodType(ConversionResult.class, String.class, InjectedValueAccess.class);
+ private static final MethodHandle HANDLE_TO_CONVERTER_CONVERTER;
+ private static final MethodHandle SUCCESSFUL_CONVERSION_FROM;
+ private static final MethodHandle FAILED_CONVERSION_FROM;
+ private static final List> PROVIDERS = ImmutableList.of(
+ ArgumentConverters::valueOfConverters,
+ ArgumentConverters::constructorConverters,
+ type -> {
+ if (Objects.equals(type.wrap().getRawType(), Character.class)) {
+ return Optional.of(SimpleArgumentConverter.from(
+ (s, c) -> SuccessfulConversion.fromSingle(s.charAt(0)),
+ "any character"
+ ));
+ }
+ return Optional.empty();
+ }
+ );
+
+ static {
+ MethodHandle handleInvoker = MethodHandles.invoker(CONVERTER_SIG);
+ try {
+ HANDLE_TO_CONVERTER_CONVERTER = LambdaMetafactory.metafactory(
+ MethodHandles.lookup(),
+ // Implementing Converter.convert
+ CONVERTER_CONVERT,
+ // Take a handle, to be converter to Converter
+ HANDLE_TO_CONVERTER,
+ // Raw signature for SAM type
+ CONVERTER_SIG,
+ // Handle to call the captured handle.
+ handleInvoker,
+ // Actual signature at invoke time
+ CONVERTER_SIG
+ ).dynamicInvoker();
+ } catch (LambdaConversionException e) {
+ throw new IllegalStateException("Failed to load ArgumentConverter MetaFactory", e);
+ }
+ }
+
+ static {
+ try {
+ SUCCESSFUL_CONVERSION_FROM = MethodHandles.lookup()
+ .findStatic(SuccessfulConversion.class, "fromSingle",
+ methodType(SuccessfulConversion.class, Object.class));
+ FAILED_CONVERSION_FROM = MethodHandles.lookup()
+ .findStatic(FailedConversion.class, "from",
+ methodType(FailedConversion.class, Throwable.class));
+ } catch (NoSuchMethodException | IllegalAccessException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private ArgumentConverters() {
+ }
public static ArgumentConverter forString() {
return STRING_ARGUMENT_CONVERTER;
@@ -99,33 +155,6 @@ private static MethodHandle noContextConverter(MethodHandle noContextHandle) {
return dropArguments(noContextHandle, 1, InjectedValueAccess.class);
}
- private static final String CONVERTER_CONVERT = "convert";
- private static final MethodType HANDLE_TO_CONVERTER = methodType(Converter.class, MethodHandle.class);
- private static final MethodType CONVERTER_SIG = methodType(ConversionResult.class, String.class, InjectedValueAccess.class);
-
- private static final MethodHandle HANDLE_TO_CONVERTER_CONVERTER;
-
- static {
- MethodHandle handleInvoker = MethodHandles.invoker(CONVERTER_SIG);
- try {
- HANDLE_TO_CONVERTER_CONVERTER = LambdaMetafactory.metafactory(
- MethodHandles.lookup(),
- // Implementing Converter.convert
- CONVERTER_CONVERT,
- // Take a handle, to be converter to Converter
- HANDLE_TO_CONVERTER,
- // Raw signature for SAM type
- CONVERTER_SIG,
- // Handle to call the captured handle.
- handleInvoker,
- // Actual signature at invoke time
- CONVERTER_SIG
- ).dynamicInvoker();
- } catch (LambdaConversionException e) {
- throw new IllegalStateException("Failed to load ArgumentConverter MetaFactory", e);
- }
- }
-
@SuppressWarnings("unchecked")
private static SimpleArgumentConverter converterForHandle(MethodHandle handle, Class> type) {
MethodType mType = handle.type();
@@ -149,22 +178,6 @@ private static SimpleArgumentConverter converterForHandle(MethodHandle ha
);
}
- private static final MethodHandle SUCCESSFUL_CONVERSION_FROM;
- private static final MethodHandle FAILED_CONVERSION_FROM;
-
- static {
- try {
- SUCCESSFUL_CONVERSION_FROM = MethodHandles.lookup()
- .findStatic(SuccessfulConversion.class, "fromSingle",
- methodType(SuccessfulConversion.class, Object.class));
- FAILED_CONVERSION_FROM = MethodHandles.lookup()
- .findStatic(FailedConversion.class, "from",
- methodType(FailedConversion.class, Throwable.class));
- } catch (NoSuchMethodException | IllegalAccessException e) {
- throw new IllegalStateException(e);
- }
- }
-
/**
* Wrap the handle to return the result using {@link ConversionResult}.
*/
@@ -178,24 +191,6 @@ private static MethodHandle augmentHandleForConversionResult(MethodHandle delega
return result;
}
- private interface ACProvider {
- Optional> provideAc(TypeToken type);
- }
-
- private static final List> PROVIDERS = ImmutableList.of(
- ArgumentConverters::valueOfConverters,
- ArgumentConverters::constructorConverters,
- type -> {
- if (Objects.equals(type.wrap().getRawType(), Character.class)) {
- return Optional.of(SimpleArgumentConverter.from(
- (s, c) -> SuccessfulConversion.fromSingle(s.charAt(0)),
- "any character"
- ));
- }
- return Optional.empty();
- }
- );
-
public static ArgumentConverter get(TypeToken type) {
if (type.getRawType().equals(String.class)) {
@SuppressWarnings("unchecked")
@@ -216,7 +211,8 @@ public static ArgumentConverter get(TypeToken type) {
return result;
}
- private ArgumentConverters() {
+ private interface ACProvider {
+ Optional> provideAc(TypeToken type);
}
}
diff --git a/core/src/main/java/org/enginehub/piston/converter/ConversionResult.java b/core/src/main/java/org/enginehub/piston/converter/ConversionResult.java
index 46550f8..5c65c1a 100644
--- a/core/src/main/java/org/enginehub/piston/converter/ConversionResult.java
+++ b/core/src/main/java/org/enginehub/piston/converter/ConversionResult.java
@@ -71,7 +71,7 @@ public abstract class ConversionResult {
*
*
* @param mapper the function to call if successful
- * @param the new type
+ * @param the new type
* @return the new result
*/
public abstract ConversionResult map(Function super Collection, ? extends Collection> mapper);
diff --git a/core/src/main/java/org/enginehub/piston/converter/Converter.java b/core/src/main/java/org/enginehub/piston/converter/Converter.java
index f2361f7..8c88533 100644
--- a/core/src/main/java/org/enginehub/piston/converter/Converter.java
+++ b/core/src/main/java/org/enginehub/piston/converter/Converter.java
@@ -37,7 +37,7 @@ public interface Converter {
*
*
* @param argument the argument input to convert
- * @param context the context to convert in
+ * @param context the context to convert in
* @return the result of attempting to convert the argument
*/
ConversionResult convert(String argument, InjectedValueAccess context);
diff --git a/core/src/main/java/org/enginehub/piston/converter/FailedConversion.java b/core/src/main/java/org/enginehub/piston/converter/FailedConversion.java
index bed94da..20919c6 100644
--- a/core/src/main/java/org/enginehub/piston/converter/FailedConversion.java
+++ b/core/src/main/java/org/enginehub/piston/converter/FailedConversion.java
@@ -28,14 +28,6 @@
public final class FailedConversion extends ConversionResult {
- public static FailedConversion from(Throwable error) {
- return from(error, ImmutableSet.of());
- }
-
- public static FailedConversion from(Throwable error, Collection> otherFailures) {
- return new FailedConversion<>(error, otherFailures);
- }
-
private final Throwable error;
private final ImmutableSet> otherFailures;
@@ -45,6 +37,13 @@ public FailedConversion(Throwable error,
this.otherFailures = ImmutableSet.copyOf(otherFailures);
}
+ public static FailedConversion from(Throwable error) {
+ return from(error, ImmutableSet.of());
+ }
+
+ public static FailedConversion from(Throwable error, Collection> otherFailures) {
+ return new FailedConversion<>(error, otherFailures);
+ }
@Override
public boolean isSuccessful() {
@@ -88,11 +87,14 @@ public Collection get() {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
FailedConversion> that = (FailedConversion>) o;
- return error.equals(that.error) &&
- otherFailures.equals(that.otherFailures);
+ return error.equals(that.error) && otherFailures.equals(that.otherFailures);
}
@Override
diff --git a/core/src/main/java/org/enginehub/piston/converter/FailedConversionMapper.java b/core/src/main/java/org/enginehub/piston/converter/FailedConversionMapper.java
index 0551476..16f06bd 100644
--- a/core/src/main/java/org/enginehub/piston/converter/FailedConversionMapper.java
+++ b/core/src/main/java/org/enginehub/piston/converter/FailedConversionMapper.java
@@ -22,6 +22,9 @@
import java.util.function.Supplier;
public class FailedConversionMapper {
+ private FailedConversionMapper() {
+ }
+
public static X mapOnto(Supplier newThrowable, FailedConversion> conversion) {
X error = newThrowable.get();
error.initCause(conversion.getError());
@@ -30,7 +33,4 @@ public static X mapOnto(Supplier newThrowable, FailedCo
);
return error;
}
-
- private FailedConversionMapper() {
- }
}
diff --git a/core/src/main/java/org/enginehub/piston/converter/MapArgumentConverter.java b/core/src/main/java/org/enginehub/piston/converter/MapArgumentConverter.java
index 9adfec3..1ed4809 100644
--- a/core/src/main/java/org/enginehub/piston/converter/MapArgumentConverter.java
+++ b/core/src/main/java/org/enginehub/piston/converter/MapArgumentConverter.java
@@ -36,6 +36,12 @@
*/
public final class MapArgumentConverter implements ArgumentConverter {
+ private final ImmutableMap map;
+
+ private MapArgumentConverter(Map map) {
+ this.map = ImmutableMap.copyOf(map);
+ }
+
/**
* Construct a converter for simple string choices from a set.
*/
@@ -49,12 +55,6 @@ public static MapArgumentConverter from(Map map) {
return new MapArgumentConverter<>(map);
}
- private final ImmutableMap map;
-
- private MapArgumentConverter(Map map) {
- this.map = ImmutableMap.copyOf(map);
- }
-
@Override
public ConversionResult convert(String argument, InjectedValueAccess context) {
T result = map.get(argument);
diff --git a/core/src/main/java/org/enginehub/piston/converter/MultiKeyConverter.java b/core/src/main/java/org/enginehub/piston/converter/MultiKeyConverter.java
index 059ea95..ac98155 100644
--- a/core/src/main/java/org/enginehub/piston/converter/MultiKeyConverter.java
+++ b/core/src/main/java/org/enginehub/piston/converter/MultiKeyConverter.java
@@ -29,12 +29,12 @@
import org.enginehub.piston.config.ColorConfig;
import org.enginehub.piston.inject.InjectedValueAccess;
-import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.UnaryOperator;
+import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Multimaps.asMap;
@@ -43,6 +43,32 @@
public class MultiKeyConverter implements ArgumentConverter {
+ private final Component choices;
+ private final ImmutableSet primaryKeys;
+ private final ImmutableMap map;
+ @Nullable
+ private final E unknownValue;
+ private final UnaryOperator errorMessage;
+
+ private MultiKeyConverter(Arguments arguments) {
+ ImmutableSortedMap.Builder map = ImmutableSortedMap.orderedBy(String.CASE_INSENSITIVE_ORDER);
+ ImmutableSet.Builder primaryKeysBuilder = ImmutableSet.builder();
+ asMap(arguments.items()).forEach((item, keys) -> {
+ checkState(keys.size() > 0, "No lookup keys for value %s", item);
+ primaryKeysBuilder.add(keys.iterator().next());
+ for (String key : keys) {
+ map.put(key, item);
+ }
+ });
+ this.primaryKeys = primaryKeysBuilder.build();
+ this.choices = primaryKeys.stream()
+ .map(ColorConfig.mainText()::wrap)
+ .collect(joiningWithBar());
+ this.map = map.build();
+ this.unknownValue = arguments.unknownValue();
+ this.errorMessage = arguments.errorMessage();
+ }
+
public static Builder builder(SetMultimap items) {
return new AutoValue_MultiKeyConverter_Arguments.Builder()
.errorMessage(arg -> "Not a valid argument: " + arg)
@@ -78,6 +104,28 @@ public static MultiKeyConverter from(Collection items,
return builder(items, lookupKeys).unknownValue(unknownValue).build();
}
+ @Override
+ public Component describeAcceptableArguments() {
+ return choices;
+ }
+
+ @Override
+ public List getSuggestions(String input, InjectedValueAccess context) {
+ return limitByPrefix(primaryKeys.stream(), input);
+ }
+
+ @Override
+ public ConversionResult convert(String argument, InjectedValueAccess context) {
+ E result = map.get(argument);
+ if (result == null) {
+ if (unknownValue != null) {
+ return SuccessfulConversion.fromSingle(unknownValue, false);
+ }
+ return FailedConversion.from(new IllegalArgumentException(errorMessage.apply(argument)));
+ }
+ return SuccessfulConversion.fromSingle(result);
+ }
+
public interface Builder {
Builder items(SetMultimap items);
@@ -91,6 +139,13 @@ public interface Builder {
@AutoValue
abstract static class Arguments {
+ abstract ImmutableSetMultimap items();
+
+ @Nullable
+ abstract E unknownValue();
+
+ abstract UnaryOperator errorMessage();
+
@AutoValue.Builder
interface Builder extends MultiKeyConverter.Builder {
@@ -111,60 +166,5 @@ default MultiKeyConverter build() {
}
}
- abstract ImmutableSetMultimap items();
-
- @Nullable
- abstract E unknownValue();
-
- abstract UnaryOperator errorMessage();
-
- }
-
- private final Component choices;
- private final ImmutableSet primaryKeys;
- private final ImmutableMap map;
- @Nullable
- private final E unknownValue;
- private final UnaryOperator errorMessage;
-
- private MultiKeyConverter(Arguments arguments) {
- ImmutableSortedMap.Builder map = ImmutableSortedMap.orderedBy(String.CASE_INSENSITIVE_ORDER);
- ImmutableSet.Builder