Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate spec on generation by default #251

Merged
merged 10 commits into from
Jul 26, 2018
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,4 @@ public void run() {
System.exit(1);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,11 @@ public class Generate implements Runnable {
description = CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DESC)
private Boolean removeOperationIdPrefix;

@Option(name = {"--skip-validate-spec"},
title = "skip spec validation",
description = "Skips the default behavior of validating an input specification.")
private Boolean skipValidateSpec;

@Override
public void run() {

Expand All @@ -207,6 +212,10 @@ public void run() {
}

// now override with any specified parameters
if (skipValidateSpec != null) {
configurator.setValidateSpec(false);
}

if (verbose != null) {
configurator.setVerbose(verbose);
}
Expand Down
5 changes: 5 additions & 0 deletions modules/openapi-generator-gradle-plugin/README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ The gradle plugin is not currently published to https://plugins.gradle.org/m2/.
|false
|The verbosity of generation

|validateSpec
|Boolean
|true
|Whether or not we should validate the input spec before generation. Invalid specs result in an error.

|generatorName
|String
|None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ gradle openApiGenerate
gradle openApiMeta
gradle openApiValidate
gradle buildGoSdk
gradle generateGoWithInvalidSpec
```

The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,16 @@ task buildGoSdk(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTas
dateLibrary: "threetenp"
]
}

task generateGoWithInvalidSpec(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask){
validateSpec = true
generatorName = "go"
inputSpec = "$rootDir/petstore-v3.0-invalid.yaml".toString()
additionalProperties = [
packageName: "petstore"
]
outputDir = "$buildDir/go".toString()
configOptions = [
dateLibrary: "threetenp"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ class OpenApiGeneratorPlugin : Plugin<Project> {
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)
generatorName.set(generate.generatorName)
outputDir.set(generate.outputDir)
inputSpec.set(generate.inputSpec)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
*/
val verbose = project.objects.property<Boolean>()

/**
* Whether or not an input specification should be validated upon generation.
*/
val validateSpec = project.objects.property<Boolean>()

/**
* The name of the generator which will handle codegen. (see "openApiGenerators" task)
*/
Expand Down Expand Up @@ -262,6 +267,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
val configOptions = project.objects.property<Map<String, String>>()

init {
applyDefaults()
}

@Suppress("MemberVisibilityCanBePrivate")
fun applyDefaults(){
releaseNote.set("Minor update")
modelNamePrefix.set("")
modelNameSuffix.set("")
Expand All @@ -271,5 +281,6 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
generateApiDocumentation.set(true)
withXml.set(false)
configOptions.set(mapOf())
validateSpec.set(true)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import org.gradle.kotlin.dsl.property
import org.openapitools.codegen.CodegenConstants
import org.openapitools.codegen.DefaultGenerator
import org.openapitools.codegen.config.CodegenConfigurator
import org.openapitools.codegen.config.CodegenConfiguratorUtils.*


/**
Expand All @@ -48,6 +47,12 @@ open class GenerateTask : DefaultTask() {
@get:Internal
val verbose = project.objects.property<Boolean>()

/**
* Whether or not an input specification should be validated upon generation.
*/
@get:Internal
val validateSpec = project.objects.property<Boolean>()

/**
* The name of the generator which will handle codegen. (see "openApiGenerators" task)
*/
Expand Down Expand Up @@ -382,6 +387,10 @@ open class GenerateTask : DefaultTask() {
configurator.isVerbose = value
}

validateSpec.ifNotEmpty { value ->
configurator.isValidateSpec = value
}

skipOverwrite.ifNotEmpty { value ->
configurator.isSkipOverwrite = value ?: false
}
Expand Down Expand Up @@ -528,8 +537,7 @@ open class GenerateTask : DefaultTask() {

out.println("Successfully generated code to ${configurator.outputDir}")
} catch (e: RuntimeException) {
logger.error(e.message)
throw GradleException("Code generation failed.")
throw GradleException("Code generation failed.", e)
}
} finally {
originalEnvironmentVariables.forEach { entry ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class GenerateTaskDslTest : TestBase() {
fun `openApiGenerate should create an expected file structure from DSL config`() {
// Arrange
val projectFiles = mapOf(
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0-invalid.yaml")
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0.yaml")
)
withProject(defaultBuildGradle, projectFiles)

Expand Down
7 changes: 6 additions & 1 deletion modules/openapi-generator-maven-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ mvn clean compile
### General Configuration parameters

- `inputSpec` - OpenAPI Spec file path
- `validateSpec` - Whether or not to validate the input spec prior to generation. Invalid specifications will result in an error.
- `language` - target generation language (deprecated, replaced by `generatorName` as values here don't represent only 'language' any longer)
- `generatorName` - target generator name
- `output` - target output path (default is `${project.build.directory}/generated-sources/swagger`)
Expand Down Expand Up @@ -102,4 +103,8 @@ Specifying a custom generator is a bit different. It doesn't support the classpa

### Sample configuration

- Please see [an example configuration](examples) for using the plugin
Please see [an example configuration](examples) for using the plugin. To run these examples, explicitly pass the file to maven. Example:

```bash
mvn -f non-java.xml compile
```
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.0.1-SNAPSHOT</version>
<version>3.1.1-SNAPSHOT</version>
<executions>
<execution>
<goals>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>sample-project</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>sample-project</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<!-- activate the plugin -->
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.1.1-SNAPSHOT</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<validateSpec>false</validateSpec>
<inputSpec>petstore-v3.0-invalid.yaml</inputSpec>
<generatorName>aspnetcore</generatorName>
<configOptions>
<additional-properties>optionalProjectFile=true</additional-properties>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.0.1-SNAPSHOT</version>
<version>3.1.1-SNAPSHOT</version>
<executions>
<execution>
<goals>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
openapi: "3.0.0"
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ public class CodeGenMojo extends AbstractMojo {

private static final Logger LOGGER = LoggerFactory.getLogger(CodeGenMojo.class);

@Parameter(name="validateSpec", required = false, defaultValue = "true")
private Boolean validateSpec;

@Parameter(name = "verbose", required = false, defaultValue = "false")
private boolean verbose;

Expand Down Expand Up @@ -348,6 +351,11 @@ public void execute() throws MojoExecutionException {

configurator.setVerbose(verbose);

// now override with any specified parameters
if (validateSpec != null) {
configurator.setValidateSpec(validateSpec);
}

if (skipOverwrite != null) {
configurator.setSkipOverwrite(skipOverwrite);
}
Expand Down
Loading