Gradle Plugin: Clean up Kotlin code (#12720)

Fix typos, unused imports and formatting issues. Remove @Supress
annotations that are no longer necessary
This commit is contained in:
Sascha Peilicke 2022-07-06 19:19:16 +02:00 committed by GitHub
parent 1a44a5284a
commit 42a45e1a1c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 137 additions and 122 deletions

View File

@ -89,7 +89,8 @@ class OpenApiGeneratorPlugin : Plugin<Project> {
register("openApiGenerate", GenerateTask::class.java).configure {
group = pluginGroup
description = "Generate code via Open API Tools Generator for Open API 2.0 or 3.x specification documents."
description =
"Generate code via Open API Tools Generator for Open API 2.0 or 3.x specification documents."
verbose.set(generate.verbose)
validateSpec.set(generate.validateSpec)

View File

@ -22,19 +22,18 @@ import org.gradle.kotlin.dsl.mapProperty
import org.gradle.kotlin.dsl.property
/**
* Gradle project level extension object definition for the generate task
* Gradle project level extension object definition for the `generate` task
*
* @author Jim Schubert
*/
open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* The verbosity of generation
*/
val verbose = project.objects.property<Boolean>()
/**
* Whether or not an input specification should be validated upon generation.
* Whether an input specification should be validated upon generation.
*/
val validateSpec = project.objects.property<Boolean>()
@ -162,17 +161,17 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
val invokerPackage = project.objects.property<String>()
/**
* GroupId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
* GroupId in generated pom.xml/build.gradle.kts or other build script. Language-specific conversions occur in non-jvm generators.
*/
val groupId = project.objects.property<String>()
/**
* ArtifactId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
* ArtifactId in generated pom.xml/build.gradle.kts or other build script. Language-specific conversions occur in non-jvm generators.
*/
val id = project.objects.property<String>()
/**
* Artifact version in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
* Artifact version in generated pom.xml/build.gradle.kts or other build script. Language-specific conversions occur in non-jvm generators.
*/
val version = project.objects.property<String>()
@ -247,7 +246,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Defines which supporting files should be generated. This allows you to create a subset of generated files (or none at all).
*
* Supporting files are those related to projects/frameworks which may be modified
* Supporting files are those related to `projects/frameworks` which may be modified
* by consumers.
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
@ -257,7 +256,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
val supportingFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines whether or not model-related _test_ files should be generated.
* Defines whether model-related _test_ files should be generated.
*
* This option enables/disables generation of ALL model-related _test_ files.
*
@ -267,7 +266,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
val generateModelTests = project.objects.property<Boolean>()
/**
* Defines whether or not model-related _documentation_ files should be generated.
* Defines whether model-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL model-related _documentation_ files.
*
@ -277,7 +276,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
val generateModelDocumentation = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _test_ files should be generated.
* Defines whether api-related _test_ files should be generated.
*
* This option enables/disables generation of ALL api-related _test_ files.
*
@ -287,7 +286,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
val generateApiTests = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _documentation_ files should be generated.
* Defines whether api-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL api-related _documentation_ files.
*

View File

@ -17,7 +17,6 @@
package org.openapitools.generator.gradle.plugin.extensions
import org.gradle.api.Project
import org.gradle.api.tasks.Internal
import org.gradle.kotlin.dsl.listProperty
import org.openapitools.codegen.meta.Stability
@ -37,7 +36,6 @@ open class OpenApiGeneratorGeneratorsExtension(project: Project) {
}
@Suppress("MemberVisibilityCanBePrivate")
fun applyDefaults(){
include.set(Stability.values().map { s -> s.value() }.filterNot { it == Stability.DEPRECATED.value() })
}
fun applyDefaults() =
include.set(Stability.values().map { it.value() }.filterNot { it == Stability.DEPRECATED.value() })
}

View File

@ -31,7 +31,7 @@ open class OpenApiGeneratorValidateExtension(project: Project) {
val inputSpec = project.objects.property<String>()
/**
* Whether or not to offer recommendations related to the validated specification document.
* Whether to offer recommendations related to the validated specification document.
*/
val recommend = project.objects.property<Boolean?>()
@ -40,7 +40,5 @@ open class OpenApiGeneratorValidateExtension(project: Project) {
}
@Suppress("MemberVisibilityCanBePrivate")
fun applyDefaults(){
recommend.set(true)
}
fun applyDefaults() = recommend.set(true)
}

View File

@ -51,7 +51,6 @@ import org.openapitools.codegen.config.GlobalSettings
@Suppress("UnstableApiUsage")
@CacheableTask
open class GenerateTask : DefaultTask() {
/**
* The verbosity of generation
*/
@ -60,7 +59,7 @@ open class GenerateTask : DefaultTask() {
val verbose = project.objects.property<Boolean>()
/**
* Whether or not an input specification should be validated upon generation.
* Whether an input specification should be validated upon generation.
*/
@Optional
@Input
@ -248,21 +247,21 @@ open class GenerateTask : DefaultTask() {
val invokerPackage = project.objects.property<String>()
/**
* GroupId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
* GroupId in generated pom.xml/build.gradle.kts or other build script. Language-specific conversions occur in non-jvm generators.
*/
@Optional
@Input
val groupId = project.objects.property<String>()
/**
* ArtifactId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
* ArtifactId in generated pom.xml/build.gradle.kts or other build script. Language-specific conversions occur in non-jvm generators.
*/
@Optional
@Input
val id = project.objects.property<String>()
/**
* Artifact version in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
* Artifact version in generated pom.xml/build.gradle.kts or other build script. Language-specific conversions occur in non-jvm generators.
*/
@Optional
@Input
@ -365,7 +364,7 @@ open class GenerateTask : DefaultTask() {
/**
* Defines which supporting files should be generated. This allows you to create a subset of generated files (or none at all).
*
* Supporting files are those related to projects/frameworks which may be modified
* Supporting files are those related to `projects/frameworks` which may be modified
* by consumers.
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
@ -377,7 +376,7 @@ open class GenerateTask : DefaultTask() {
val supportingFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines whether or not model-related _test_ files should be generated.
* Defines whether model-related _test_ files should be generated.
*
* This option enables/disables generation of ALL model-related _test_ files.
*
@ -389,7 +388,7 @@ open class GenerateTask : DefaultTask() {
val generateModelTests = project.objects.property<Boolean>()
/**
* Defines whether or not model-related _documentation_ files should be generated.
* Defines whether model-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL model-related _documentation_ files.
*
@ -401,7 +400,7 @@ open class GenerateTask : DefaultTask() {
val generateModelDocumentation = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _test_ files should be generated.
* Defines whether api-related _test_ files should be generated.
*
* This option enables/disables generation of ALL api-related _test_ files.
*
@ -413,7 +412,7 @@ open class GenerateTask : DefaultTask() {
val generateApiTests = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _documentation_ files should be generated.
* Defines whether api-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL api-related _documentation_ files.
*
@ -511,7 +510,10 @@ open class GenerateTask : DefaultTask() {
}
if (supportingFilesConstrainedTo.isPresent && supportingFilesConstrainedTo.get().isNotEmpty()) {
GlobalSettings.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesConstrainedTo.get().joinToString(","))
GlobalSettings.setProperty(
CodegenConstants.SUPPORTING_FILES,
supportingFilesConstrainedTo.get().joinToString(",")
)
} else {
GlobalSettings.clearProperty(CodegenConstants.SUPPORTING_FILES)
}
@ -748,11 +750,11 @@ open class GenerateTask : DefaultTask() {
}
val clientOptInput = configurator.toClientOptInput()
val codgenConfig = clientOptInput.config
val codegenConfig = clientOptInput.config
if (configOptions.isPresent) {
val userSpecifiedConfigOptions = configOptions.get()
codgenConfig.cliOptions().forEach {
codegenConfig.cliOptions().forEach {
if (userSpecifiedConfigOptions.containsKey(it.opt)) {
clientOptInput.config.additionalProperties()[it.opt] = userSpecifiedConfigOptions[it.opt]
}

View File

@ -43,7 +43,6 @@ open class GeneratorsTask : DefaultTask() {
@get:Internal
val include = project.objects.listProperty<String>()
@Suppress("unused")
@TaskAction
fun doWork() {
val generators = CodegenConfigLoader.getAll()

View File

@ -44,7 +44,6 @@ import java.nio.charset.Charset
*/
@CacheableTask
open class MetaTask : DefaultTask() {
@get:Input
val generatorName = project.objects.property<String>()
@ -54,10 +53,8 @@ open class MetaTask : DefaultTask() {
@get:OutputDirectory
val outputFolder = project.objects.property<String>()
@Suppress("unused")
@TaskAction
fun doWork() {
val packageToPath = packageName.get().replace(".", File.separator)
val dir = File(outputFolder.get())
val klass = "${generatorName.get().titleCasedTextOnly()}Generator"
@ -79,15 +76,22 @@ open class MetaTask : DefaultTask() {
SupportingFile("api.template", dir("src", "main", "resources", templateResourceDir), "api.mustache"),
SupportingFile("model.template", dir("src", "main", "resources", templateResourceDir), "model.mustache"),
SupportingFile("myFile.template", dir("src", "main", "resources", templateResourceDir), "myFile.mustache"),
SupportingFile("services.mustache", dir("src", "main", "resources", "META-INF", "services"), CodegenConfig::class.java.canonicalName))
SupportingFile(
"services.mustache",
dir("src", "main", "resources", "META-INF", "services"),
CodegenConfig::class.java.canonicalName
)
)
val currentVersion = CodegenConstants::class.java.`package`.implementationVersion
val data = mapOf("generatorPackage" to packageToPath,
val data = mapOf(
"generatorPackage" to packageToPath,
"generatorClass" to klass,
"name" to templateResourceDir,
"fullyQualifiedGeneratorClass" to "${packageName.get()}.$klass",
"openapiGeneratorVersion" to currentVersion)
"openapiGeneratorVersion" to currentVersion
)
supportingFiles.map {
try {
@ -131,11 +135,10 @@ open class MetaTask : DefaultTask() {
}
private fun String.titleCasedTextOnly(): String =
this.split(Regex("[^a-zA-Z0-9]")).joinToString(separator = "", transform = String::capitalize)
split(Regex("[^a-zA-Z0-9]")).joinToString(separator = "", transform = String::capitalize)
private fun String.hyphenatedTextOnly(): String =
this.split(Regex("[^a-zA-Z0-9]")).joinToString(separator = "-", transform = String::toLowerCase)
split(Regex("[^a-zA-Z0-9]")).joinToString(separator = "-", transform = String::toLowerCase)
private fun dir(vararg parts: String): String =
parts.joinToString(separator = File.separator)
private fun dir(vararg parts: String): String = parts.joinToString(separator = File.separator)
}

View File

@ -14,8 +14,6 @@
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package org.openapitools.generator.gradle.plugin.tasks
import io.swagger.parser.OpenAPIParser
@ -45,7 +43,7 @@ import org.openapitools.codegen.validations.oas.RuleConfiguration
*
* ./gradlew openApiValidate --input=/path/to/file
*
* build.gradle:
* build.gradle.kts:
*
* openApiMeta {
* inputSpec = "path/to/spec.yaml"
@ -62,7 +60,6 @@ open class ValidateTask : DefaultTask() {
@Input
val recommend = project.objects.property<Boolean?>()
@Suppress("unused")
@get:Internal
@set:Option(option = "input", description = "The input specification.")
var input: String? = null
@ -70,7 +67,6 @@ open class ValidateTask : DefaultTask() {
inputSpec.set(value)
}
@Suppress("unused")
@TaskAction
fun doWork() {
val logger = Logging.getLogger(javaClass)
@ -105,7 +101,6 @@ open class ValidateTask : DefaultTask() {
}
if (messages.isNotEmpty() || validationResult.errors.isNotEmpty()) {
out.withStyle(StyledTextOutput.Style.Error)
out.println("\nSpec is invalid.\nIssues:\n")

View File

@ -4,12 +4,13 @@ import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.testng.annotations.Test
import java.io.File
import java.nio.file.Files.createTempDirectory
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class GenerateTaskDslTest : TestBase() {
override var temp: File = createTempDir(javaClass.simpleName)
override var temp: File = createTempDirectory(javaClass.simpleName).toFile()
private val defaultBuildGradle = """
plugins {
@ -61,7 +62,7 @@ class GenerateTaskDslTest : TestBase() {
"build/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt"
).map {
val f = File(temp, it)
assertTrue(f.exists() && f.isFile, "An expected file was not generated when invoking the generation.")
assertTrue(f.exists() && f.isFile, "An expected file was not generated when invoking the generation: $f")
}
assertEquals(TaskOutcome.SUCCESS, result.task(":openApiGenerate")?.outcome,
@ -110,7 +111,7 @@ class GenerateTaskDslTest : TestBase() {
"build/java/src/main/java/org/openapitools/example/api/PetsApiClassSuffix.java"
).map {
val f = File(temp, it)
assertTrue(f.exists() && f.isFile, "An expected file was not generated when invoking the generation. - " + f)
assertTrue(f.exists() && f.isFile, "An expected file was not generated when invoking the generation. - $f")
}
assertEquals(TaskOutcome.SUCCESS, result.task(":openApiGenerate")?.outcome,

View File

@ -27,7 +27,7 @@ class GeneratorsTaskDslTest : TestBase() {
.build()
// Assert
assertTrue(result.output.contains("The following generators are available:"), "User friendly generator notice is missing.")
assertTrue(result.output.contains("The following generators are available:"), "User-friendly generator notice is missing.")
assertTrue(result.output.contains("CLIENT generators:"), "Expected client generator header is missing.")
assertTrue(result.output.contains("android"), "Spot-checking listed client generators is missing a client generator.")
assertTrue(result.output.contains("SERVER generators:"), "Expected server generator header is missing.")

View File

@ -34,7 +34,7 @@ class MetaTaskDslTest : TestBase() {
.build()
// Assert
assertTrue(result.output.contains("Wrote file to"), "User friendly write notice is missing.")
assertTrue(result.output.contains("Wrote file to"), "User-friendly write notice is missing.")
// To avoid any OS-specific output causing issues with our stdout comparisons, only compare on expected filenames.
listOf(

View File

@ -4,13 +4,14 @@ import org.testng.annotations.AfterMethod
import org.testng.annotations.BeforeMethod
import java.io.File
import java.io.InputStream
import java.nio.file.Files.createTempDirectory
abstract class TestBase {
protected open lateinit var temp: File
@BeforeMethod
protected fun before() {
temp = createTempDir(javaClass.simpleName)
temp = createTempDirectory(javaClass.simpleName).toFile()
temp.deleteOnExit()
}
@ -19,12 +20,8 @@ abstract class TestBase {
temp.deleteRecursively()
}
protected fun withProject(
buildContents: String,
projectFiles: Map<String, InputStream> = mapOf()
) {
val buildFile = File(temp,"build.gradle")
buildFile.writeText(buildContents)
protected fun withProject(buildContents: String, projectFiles: Map<String, InputStream> = mapOf()) {
File(temp, "build.gradle").writeText(buildContents)
projectFiles.forEach { entry ->
val target = File(temp, entry.key)

View File

@ -7,18 +7,20 @@ import org.gradle.util.GradleVersion
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import java.io.File
import java.nio.file.Files.createTempDirectory
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ValidateTaskDslTest : TestBase() {
override var temp: File = createTempDir(javaClass.simpleName)
override var temp: File = createTempDirectory(javaClass.simpleName).toFile()
@DataProvider(name = "gradle_version_provider")
fun gradleVersionProvider(): Array<Array<String?>> = arrayOf(
arrayOf(null), // uses the version of Gradle used to build the plugin itself
arrayOf("5.6.4"),
arrayOf("6.9"),
arrayOf("7.0"))
arrayOf("7.0")
)
private fun getGradleRunner(gradleVersion: String?): GradleRunner {
val gradleRunner = GradleRunner.create()
@ -33,7 +35,8 @@ class ValidateTaskDslTest : TestBase() {
@Test(dataProvider = "gradle_version_provider")
fun `openApiValidate should fail on non-file spec`(gradleVersion: String?) {
// Arrange
withProject("""
withProject(
"""
| plugins {
| id 'org.openapi.generator'
| }
@ -41,7 +44,8 @@ class ValidateTaskDslTest : TestBase() {
| openApiValidate {
| inputSpec = "some_location"
| }
""".trimMargin())
""".trimMargin()
)
// Act
val result = getGradleRunner(gradleVersion)
@ -59,9 +63,14 @@ class ValidateTaskDslTest : TestBase() {
} else {
"An input file was expected to be present but it doesn't exist."
}
assertTrue(result.output.contains(expectedMessage), "Unexpected/no message presented to the user for a spec pointing to an invalid URI.")
assertEquals(FAILED, result.task(":openApiValidate")?.outcome,
"Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}")
assertTrue(
result.output.contains(expectedMessage),
"Unexpected/no message presented to the user for a spec pointing to an invalid URI."
)
assertEquals(
FAILED, result.task(":openApiValidate")?.outcome,
"Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}"
)
}
@Test(dataProvider = "gradle_version_provider")
@ -71,7 +80,8 @@ class ValidateTaskDslTest : TestBase() {
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0.yaml")
)
withProject("""
withProject(
"""
| plugins {
| id 'org.openapi.generator'
| }
@ -79,7 +89,8 @@ class ValidateTaskDslTest : TestBase() {
| openApiValidate {
| inputSpec = file("spec.yaml").absolutePath
| }
""".trimMargin(), projectFiles)
""".trimMargin(), projectFiles
)
// Act
val result = getGradleRunner(gradleVersion)
@ -89,9 +100,14 @@ class ValidateTaskDslTest : TestBase() {
.build()
// Assert
assertTrue(result.output.contains("Spec is valid."), "Unexpected/no message presented to the user for a valid spec.")
assertEquals(SUCCESS, result.task(":openApiValidate")?.outcome,
"Expected a successful run, but found ${result.task(":openApiValidate")?.outcome}")
assertTrue(
result.output.contains("Spec is valid."),
"Unexpected/no message presented to the user for a valid spec."
)
assertEquals(
SUCCESS, result.task(":openApiValidate")?.outcome,
"Expected a successful run, but found ${result.task(":openApiValidate")?.outcome}"
)
}
@Test(dataProvider = "gradle_version_provider")
@ -100,7 +116,8 @@ class ValidateTaskDslTest : TestBase() {
val projectFiles = mapOf(
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0-invalid.yaml")
)
withProject("""
withProject(
"""
| plugins {
| id 'org.openapi.generator'
| }
@ -108,7 +125,8 @@ class ValidateTaskDslTest : TestBase() {
| openApiValidate {
| inputSpec = file('spec.yaml').absolutePath
| }
""".trimMargin(), projectFiles)
""".trimMargin(), projectFiles
)
// Act
val result = getGradleRunner(gradleVersion)
@ -118,9 +136,13 @@ class ValidateTaskDslTest : TestBase() {
.buildAndFail()
// Assert
assertTrue(result.output.contains("Spec is invalid."), "Unexpected/no message presented to the user for an invalid spec.")
assertEquals(FAILED, result.task(":openApiValidate")?.outcome,
"Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}")
assertTrue(
result.output.contains("Spec is invalid."),
"Unexpected/no message presented to the user for an invalid spec."
)
assertEquals(
FAILED, result.task(":openApiValidate")?.outcome,
"Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}"
)
}
}