[maven]📝 Docs and minor refactoring (#5251)

The maven documentation was missing a few option, a couple of option
properties, and was inconsistent regarding selective generation for apis
an models. This adds properties and options where appropriate and
updates the docs. All options in the README have been reordered to match
property declaration order in CodegenMojo, hopefully making it easier
for maintainers to recognized when there are docs missing or out of
date.

This also slightly refactors the code in CodegenMojo to reduce the
cyclomatic complexity of the `execute` method.
This commit is contained in:
Jim Schubert 2020-02-08 20:50:14 -05:00 committed by GitHub
parent 561335f5e5
commit 4602596df2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 139 additions and 96 deletions

View File

@ -43,57 +43,96 @@ mvn clean compile
| Option | Property | Description |
|--------|----------|-------------|
| `verbose` | `openapi.generator.maven.plugin.verbose` | verbose mode (`false` by default)
| `inputSpec` | `openapi.generator.maven.plugin.inputSpec` | OpenAPI Spec file path
| `language` | `openapi.generator.maven.plugin.language` | target generation language (deprecated, replaced by `generatorName` as values here don't represent only 'language' any longer)
| `generatorName` | `openapi.generator.maven.plugin.generatorName` | target generator name
| `output` | `openapi.generator.maven.plugin.output` | target output path (default is `${project.build.directory}/generated-sources/openapi`. Can also be set globally through the `openapi.generator.maven.plugin.output` property)
| `gitHost` | `openapi.generator.maven.plugin.gitHost` | The git host, e.g. gitlab.com
| `gitUserId` | `openapi.generator.maven.plugin.gitUserId` | sets git information of the project
| `gitRepoId` | `openapi.generator.maven.plugin.gitRepoId` | sets the repo ID (e.g. openapi-generator)
| `templateDirectory` | `openapi.generator.maven.plugin.templateDirectory` | directory with mustache templates
| `templateResourcePath` | `openapi.generator.maven.plugin.templateResourcePath` | directory with mustache templates via resource path. This option will overwrite any option defined in `templateDirectory`.
| `addCompileSourceRoot` | `openapi.generator.maven.plugin.addCompileSourceRoot` | add the output directory to the project as a source root (`true` by default)
| `modelPackage` | `openapi.generator.maven.plugin.modelPackage` | the package to use for generated model objects/classes
| `templateResourcePath` | `openapi.generator.maven.plugin.templateResourcePath` | directory with mustache templates via resource path. This option will overwrite any option defined in `templateDirectory`.
| `engine` | `openapi.generator.maven.plugin.engine` | The name of templating engine to use, "mustache" (default) or "handlebars" (beta)
| `auth` | `openapi.generator.maven.plugin.auth` | adds authorization headers when fetching the OpenAPI definitions remotely. Pass in a URL-encoded string of `name:header` with a comma separating multiple values
| `configurationFile` | `openapi.generator.maven.plugin.configurationFile` | Path to separate json configuration file. File content should be in a json format {"optionKey":"optionValue", "optionKey1":"optionValue1"...} Supported options can be different for each language. Run `config-help -g {generator name}` command for language specific config options
| `skipOverwrite` | `openapi.generator.maven.plugin.skipOverwrite` | Specifies if the existing files should be overwritten during the generation. (`false` by default)
| `apiPackage` | `openapi.generator.maven.plugin.apiPackage` | the package to use for generated api objects/classes
| `modelPackage` | `openapi.generator.maven.plugin.modelPackage` | the package to use for generated model objects/classes
| `invokerPackage` | `openapi.generator.maven.plugin.invokerPackage` | the package to use for the generated invoker objects
| `packageName` | `openapi.generator.maven.plugin.packageName` | the default package name to use for the generated objects
| `groupId` | `openapi.generator.maven.plugin.groupId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators
| `artifactId` | `openapi.generator.maven.plugin.artifactId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators
| `artifactVersion` | `openapi.generator.maven.plugin.artifactVersion` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators
| `library` | `openapi.generator.maven.plugin.library` | library template (sub-template)
| `modelNamePrefix` | `openapi.generator.maven.plugin.modelNamePrefix` | Sets the prefix for model classes and enums
| `modelNameSuffix` | `openapi.generator.maven.plugin.modelNameSuffix` | Sets the suffix for model classes and enums
| `withXml` | `openapi.generator.maven.plugin.withXml` | enable XML annotations inside the generated models and API (only works with Java `language` and libraries that provide support for JSON and XML)
| `configOptions` | N/A | a map of language-specific parameters. To show a full list of generator-specified parameters (options), please use `configHelp` (explained below)
| `configHelp` | `codegen.configHelp` | dumps the configuration help for the specified library (generates no sources)
| `ignoreFileOverride` | `openapi.generator.maven.plugin.ignoreFileOverride` | specifies the full path to a `.openapi-generator-ignore` used for pattern based overrides of generated outputs
| `httpUserAgent` | `openapi.generator.maven.plugin.httpUserAgent` | Sets custom User-Agent header value
| `removeOperationIdPrefix` | `openapi.generator.maven.plugin.removeOperationIdPrefix` | remove operationId prefix (e.g. user_getName => getName)
| `logToStderr` | `openapi.generator.maven.plugin.logToStderr` | write all log messages (not just errors) to STDOUT
| `enablePostProcessFile` | `openapi.generator.maven.plugin.` | enable file post-processing hook
| `skipValidateSpec` | `openapi.generator.maven.plugin.skipValidateSpec` | Whether or not to skip validating the input spec prior to generation. By default, invalid specifications will result in an error.
| `strictSpec` | `openapi.generator.maven.plugin.strictSpec` | Whether or not to treat an input document strictly against the spec. 'MUST' and 'SHALL' wording in OpenAPI spec is strictly adhered to. e.g. when false, no fixes will be applied to documents which pass validation but don't follow the spec.
| `generateAliasAsModel` | `openapi.generator.maven.plugin.generateAliasAsModel` | generate alias (array, map) as model
| `generateApis` | `openapi.generator.maven.plugin.generateApis` | generate the apis (`true` by default)
| `generateApiTests` | `openapi.generator.maven.plugin.generateApiTests` | generate the api tests (`true` by default. Only available if `generateApis` is `true`)
| `generateApiDocumentation` | `openapi.generator.maven.plugin.generateApiDocumentation` | generate the api documentation (`true` by default. Only available if `generateApis` is `true`)
| `generateModels` | `openapi.generator.maven.plugin.generateModels` | generate the models (`true` by default)
| `modelsToGenerate` | `openapi.generator.maven.plugin.modelsToGenerate` | A comma separated list of models to generate. All models is the default.
| `generateModelTests` | `openapi.generator.maven.plugin.generateModelTests` | generate the model tests (`true` by default. Only available if `generateModels` is `true`)
| `generateModelDocumentation` | `openapi.generator.maven.plugin.generateModelDocumentation` | generate the model documentation (`true` by default. Only available if `generateModels` is `true`)
| `generateSupportingFiles` | `openapi.generator.maven.plugin.generateSupportingFiles` | generate the supporting files (`true` by default)
| `supportingFilesToGenerate` | `openapi.generator.maven.plugin.supportingFilesToGenerate` | A comma separated list of supporting files to generate. All files is the default.
| `skip` | `codegen.skip` | skip code generation (`false` by default. Can also be set globally through the `codegen.skip` property)
| `verbose` | `openapi.generator.maven.plugin.verbose` | verbose mode (`false` by default)
| `groupId` | `openapi.generator.maven.plugin.groupId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators
| `artifactId` | `openapi.generator.maven.plugin.artifactId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators
| `artifactVersion` | `openapi.generator.maven.plugin.artifactVersion` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators
| `gitUserId` and `gitRepoId` | `openapi.generator.maven.plugin.gitUserId` | sets git information of the project
| `auth` | `openapi.generator.maven.plugin.auth` | adds authorization headers when fetching the OpenAPI definitions remotely. Pass in a URL-encoded string of `name:header` with a comma separating multiple values
| `configurationFile` | `openapi.generator.maven.plugin.configurationFile` | Path to separate json configuration file. File content should be in a json format {"optionKey":"optionValue", "optionKey1":"optionValue1"...} Supported options can be different for each language. Run `config-help -g {generator name}` command for language specific config options
| `skipOverwrite` | `openapi.generator.maven.plugin.skipOverwrite` | Specifies if the existing files should be overwritten during the generation. (`false` by default)
| `library` | `openapi.generator.maven.plugin.library` | library template (sub-template)
| `configOptions` | N/A | a **map** of language-specific parameters. To show a full list of generator-specified parameters (options), please use `configHelp` (explained below)
| `instantiationTypes` | `openapi.generator.maven.plugin.instantiationTypes` | sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType. For example (in Java): `array=ArrayList,map=HashMap`. In other words array types will get instantiated as ArrayList in generated code. You can also have multiple occurrences of this option
| `importMappings` | `openapi.generator.maven.plugin.importMappings` | specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import. You can also have multiple occurrences of this option
| `typeMappings` | `openapi.generator.maven.plugin.typeMappings` | sets mappings between OpenAPI spec types and generated code types in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: `array=List,map=Map,string=String`. You can also have multiple occurrences of this option
| `languageSpecificPrimitives` | `openapi.generator.maven.plugin.languageSpecificPrimitives` | specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: `String,boolean,Boolean,Double`. You can also have multiple occurrences of this option
| `additionalProperties` | `openapi.generator.maven.plugin.additionalProperties` | sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value. You can also have multiple occurrences of this option
| `serverVariableOverrides` | `openapi.generator.maven.plugin.serverVariableOverrides` | A map of server variable overrides for specs that support server URL templating
| `reservedWordsMappings` | `openapi.generator.maven.plugin.reservedWordsMappings` | specifies how a reserved name should be escaped to. Otherwise, the default `_<name>` is used. For example `id=identifier`. You can also have multiple occurrences of this option
| `generateApis` | `openapi.generator.maven.plugin.generateApis` | generate the apis (`true` by default). Specific apis may be defined as a CSV via `apisToGenerate`.
| `apisToGenerate` | `openapi.generator.maven.plugin.apisToGenerate` | A comma separated list of apis to generate. All apis is the default.
| `generateModels` | `openapi.generator.maven.plugin.generateModels` | generate the models (`true` by default). Specific models may be defined as a CSV via `modelsToGenerate`.
| `modelsToGenerate` | `openapi.generator.maven.plugin.modelsToGenerate` | A comma separated list of models to generate. All models is the default.
| `generateSupportingFiles` | `openapi.generator.maven.plugin.generateSupportingFiles` | generate the supporting files (`true` by default)
| `supportingFilesToGenerate` | `openapi.generator.maven.plugin.supportingFilesToGenerate` | A comma separated list of supporting files to generate. All files is the default.
| `generateModelTests` | `openapi.generator.maven.plugin.generateModelTests` | generate the model tests (`true` by default. Only available if `generateModels` is `true`)
| `generateModelDocumentation` | `openapi.generator.maven.plugin.generateModelDocumentation` | generate the model documentation (`true` by default. Only available if `generateModels` is `true`)
| `generateApiTests` | `openapi.generator.maven.plugin.generateApiTests` | generate the api tests (`true` by default. Only available if `generateApis` is `true`)
| `generateApiDocumentation` | `openapi.generator.maven.plugin.generateApiDocumentation` | generate the api documentation (`true` by default. Only available if `generateApis` is `true`)
| `withXml` | `openapi.generator.maven.plugin.withXml` | enable XML annotations inside the generated models and API (only works with Java `language` and libraries that provide support for JSON and XML)
| `skip` | `codegen.skip` | skip code generation (`false` by default. Can also be set globally through the `codegen.skip` property)
| `skipIfSpecIsUnchanged` | `codegen.skipIfSpecIsUnchanged` | Skip the execution if the source file is older than the output folder (`false` by default. Can also be set globally through the `codegen.skipIfSpecIsUnchanged` property)
| `engine` | `openapi.generator.maven.plugin.engine` | The name of templating engine to use, "mustache" (default) or "handlebars" (beta)
| `httpUserAgent` | `openapi.generator.maven.plugin.httpUserAgent` | Sets custom User-Agent header value
| `addCompileSourceRoot` | `openapi.generator.maven.plugin.addCompileSourceRoot` | add the output directory to the project as a source root (`true` by default)
| `environmentVariables` | N/A | A **map** of items conceptually similar to "environment variables" or "system properties". These are merged into a map of global settings available to all aspects of the generation flow. Use this map for any options documented elsewhere as `systemProperties`.
| `configHelp` | `codegen.configHelp` | dumps the configuration help for the specified library (generates no sources)
### Configuring **map** structures
For configuration options documented as a **map** above, the key/value options may be configured as free-form nodes under these options. This takes the format:
```xml
<configuration>
<option>
<key>value</key>
</option>
</configuration>
```
This configuration node location will match that of the plugin configuration examples at the top of this document and in the section below. Here, `option` matches in option name in the first column in the table from the previous section.
The `key` and `value` text are any values you'd like to provide for that option. As an example, to configure `environmentVariables` to match the `-Dmodels=User,Pet` example from our [Selective Generation](https://openapi-generator.tech/docs/customization#selective-generation) documentation, see below.
```xml
<configuration>
<environmentVariables>
<models>User,Pet</models>
</environmentVariables>
</configuration>
```
Not that some of these environment variable options may overwrite or conflict with other options available to the maven plugin. For example, the above `environmentVariables` example is equivalent to the following:
```xml
<configuration>
<generateModels>true</generateModels>
<modelsToGenerate>User,Pet</modelsToGenerate>
</configuration>
```
The difference here is that you may define `generateModels` and `modelsToGenerate` as properties, while `environmentVariables` may only be configured as a configuration node.
### Custom Generator

View File

@ -32,6 +32,7 @@ import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -62,13 +63,13 @@ import org.sonatype.plexus.build.incremental.DefaultBuildContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
/**
* Goal which generates client/server code from a OpenAPI json/yaml definition.
*/
@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"})
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class CodeGenMojo extends AbstractMojo {
@ -81,9 +82,10 @@ public class CodeGenMojo extends AbstractMojo {
@Component
private BuildContext buildContext = new DefaultBuildContext();
@Parameter(name = "verbose", required = false, defaultValue = "false")
@Parameter(name = "verbose", defaultValue = "false")
private boolean verbose;
// TODO: 5.0 Remove `language` option.
/**
* Client language to generate.
*/
@ -94,7 +96,7 @@ public class CodeGenMojo extends AbstractMojo {
/**
* The name of the generator to use.
*/
@Parameter(name = "generatorName")
@Parameter(name = "generatorName", property = "openapi.generator.maven.plugin.generatorName")
private String generatorName;
/**
@ -113,19 +115,19 @@ public class CodeGenMojo extends AbstractMojo {
/**
* Git host, e.g. gitlab.com.
*/
@Parameter(name = "gitHost", property = "openapi.generator.maven.plugin.gitHost", required = false)
@Parameter(name = "gitHost", property = "openapi.generator.maven.plugin.gitHost")
private String gitHost;
/**
* Git user ID, e.g. swagger-api.
*/
@Parameter(name = "gitUserId", property = "openapi.generator.maven.plugin.gitUserId", required = false)
@Parameter(name = "gitUserId", property = "openapi.generator.maven.plugin.gitUserId")
private String gitUserId;
/**
* Git repo ID, e.g. openapi-generator.
*/
@Parameter(name = "gitRepoId", property = "openapi.generator.maven.plugin.gitRepoId", required = false)
@Parameter(name = "gitRepoId", property = "openapi.generator.maven.plugin.gitRepoId")
private String gitRepoId;
/**
@ -156,13 +158,13 @@ public class CodeGenMojo extends AbstractMojo {
/**
* Path to separate json configuration file.
*/
@Parameter(name = "configurationFile", property = "openapi.generator.maven.plugin.configurationFile", required = false)
@Parameter(name = "configurationFile", property = "openapi.generator.maven.plugin.configurationFile")
private String configurationFile;
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@Parameter(name = "skipOverwrite", property = "openapi.generator.maven.plugin.skipOverwrite", required = false)
@Parameter(name = "skipOverwrite", property = "openapi.generator.maven.plugin.skipOverwrite")
private Boolean skipOverwrite;
/**
@ -210,67 +212,67 @@ public class CodeGenMojo extends AbstractMojo {
/**
* Sets the library
*/
@Parameter(name = "library", property = "openapi.generator.maven.plugin.library", required = false)
@Parameter(name = "library", property = "openapi.generator.maven.plugin.library")
private String library;
/**
* Sets the prefix for model enums and classes
*/
@Parameter(name = "modelNamePrefix", property = "openapi.generator.maven.plugin.modelNamePrefix", required = false)
@Parameter(name = "modelNamePrefix", property = "openapi.generator.maven.plugin.modelNamePrefix")
private String modelNamePrefix;
/**
* Sets the suffix for model enums and classes
*/
@Parameter(name = "modelNameSuffix", property = "openapi.generator.maven.plugin.modelNameSuffix", required = false)
@Parameter(name = "modelNameSuffix", property = "openapi.generator.maven.plugin.modelNameSuffix")
private String modelNameSuffix;
/**
* Sets an optional ignoreFileOverride path
*/
@Parameter(name = "ignoreFileOverride", property = "openapi.generator.maven.plugin.ignoreFileOverride", required = false)
@Parameter(name = "ignoreFileOverride", property = "openapi.generator.maven.plugin.ignoreFileOverride")
private String ignoreFileOverride;
/**
* Sets custom User-Agent header value
*/
@Parameter(name = "httpUserAgent", property = "openapi.generator.maven.plugin.httpUserAgent", required = false)
@Parameter(name = "httpUserAgent", property = "openapi.generator.maven.plugin.httpUserAgent")
private String httpUserAgent;
/**
* To remove operationId prefix (e.g. user_getName => getName)
*/
@Parameter(name = "removeOperationIdPrefix", property = "openapi.generator.maven.plugin.removeOperationIdPrefix", required = false)
@Parameter(name = "removeOperationIdPrefix", property = "openapi.generator.maven.plugin.removeOperationIdPrefix")
private Boolean removeOperationIdPrefix;
/**
* To write all log messages (not just errors) to STDOUT
*/
@Parameter(name = "logToStderr", property = "openapi.generator.maven.plugin.logToStderr", required = false)
@Parameter(name = "logToStderr", property = "openapi.generator.maven.plugin.logToStderr")
private Boolean logToStderr;
/**
* To file post-processing hook
*/
@Parameter(name = "enablePostProcessFile", property = "openapi.generator.maven.plugin.enablePostProcessFile", required = false)
@Parameter(name = "enablePostProcessFile", property = "openapi.generator.maven.plugin.enablePostProcessFile")
private Boolean enablePostProcessFile;
/**
* To skip spec validation
*/
@Parameter(name = "skipValidateSpec", property = "openapi.generator.maven.plugin.skipValidateSpec", required = false)
@Parameter(name = "skipValidateSpec", property = "openapi.generator.maven.plugin.skipValidateSpec")
private Boolean skipValidateSpec;
/**
* To treat a document strictly against the spec.
*/
@Parameter(name = "strictSpec", property = "openapi.generator.maven.plugin.strictSpec", required = false)
@Parameter(name = "strictSpec", property = "openapi.generator.maven.plugin.strictSpec")
private Boolean strictSpec;
/**
* To generate alias (array, map) as model
*/
@Parameter(name = "generateAliasAsModel", property = "openapi.generator.maven.plugin.generateAliasAsModel", required = false)
@Parameter(name = "generateAliasAsModel", property = "openapi.generator.maven.plugin.generateAliasAsModel")
private Boolean generateAliasAsModel;
/**
@ -324,87 +326,93 @@ public class CodeGenMojo extends AbstractMojo {
/**
* Generate the apis
*/
@Parameter(name = "generateApis", property = "openapi.generator.maven.plugin.generateApis", required = false)
@Parameter(name = "generateApis", property = "openapi.generator.maven.plugin.generateApis")
private Boolean generateApis = true;
/**
* A comma separated list of apis to generate. All apis is the default.
*/
@Parameter(name = "apisToGenerate", property = "openapi.generator.maven.plugin.apisToGenerate")
private String apisToGenerate = "";
/**
* Generate the models
*/
@Parameter(name = "generateModels", property = "openapi.generator.maven.plugin.generateModels", required = false)
@Parameter(name = "generateModels", property = "openapi.generator.maven.plugin.generateModels")
private Boolean generateModels = true;
/**
* A comma separated list of models to generate. All models is the default.
*/
@Parameter(name = "modelsToGenerate", property = "openapi.generator.maven.plugin.modelsToGenerate", required = false)
@Parameter(name = "modelsToGenerate", property = "openapi.generator.maven.plugin.modelsToGenerate")
private String modelsToGenerate = "";
/**
* Generate the supporting files
*/
@Parameter(name = "generateSupportingFiles", property = "openapi.generator.maven.plugin.generateSupportingFiles", required = false)
@Parameter(name = "generateSupportingFiles", property = "openapi.generator.maven.plugin.generateSupportingFiles")
private Boolean generateSupportingFiles = true;
/**
* A comma separated list of models to generate. All models is the default.
*/
@Parameter(name = "supportingFilesToGenerate", property = "openapi.generator.maven.plugin.supportingFilesToGenerate", required = false)
@Parameter(name = "supportingFilesToGenerate", property = "openapi.generator.maven.plugin.supportingFilesToGenerate")
private String supportingFilesToGenerate = "";
/**
* Generate the model tests
*/
@Parameter(name = "generateModelTests", property = "openapi.generator.maven.plugin.generateModelTests", required = false)
@Parameter(name = "generateModelTests", property = "openapi.generator.maven.plugin.generateModelTests")
private Boolean generateModelTests = true;
/**
* Generate the model documentation
*/
@Parameter(name = "generateModelDocumentation", property = "openapi.generator.maven.plugin.generateModelDocumentation", required = false)
@Parameter(name = "generateModelDocumentation", property = "openapi.generator.maven.plugin.generateModelDocumentation")
private Boolean generateModelDocumentation = true;
/**
* Generate the api tests
*/
@Parameter(name = "generateApiTests", property = "openapi.generator.maven.plugin.generateApiTests", required = false)
@Parameter(name = "generateApiTests", property = "openapi.generator.maven.plugin.generateApiTests")
private Boolean generateApiTests = true;
/**
* Generate the api documentation
*/
@Parameter(name = "generateApiDocumentation", property = "openapi.generator.maven.plugin.generateApiDocumentation", required = false)
@Parameter(name = "generateApiDocumentation", property = "openapi.generator.maven.plugin.generateApiDocumentation")
private Boolean generateApiDocumentation = true;
/**
* Generate the api documentation
*/
@Parameter(name = "withXml", property = "openapi.generator.maven.plugin.withXml", required = false)
@Parameter(name = "withXml", property = "openapi.generator.maven.plugin.withXml")
private Boolean withXml = false;
/**
* Skip the execution.
*/
@Parameter(name = "skip", property = "codegen.skip", required = false, defaultValue = "false")
@Parameter(name = "skip", property = "codegen.skip", defaultValue = "false")
private Boolean skip;
/**
* Skip the execution if the source file is older than the output folder.
*/
@Parameter(name = "skipIfSpecIsUnchanged", property = "codegen.skipIfSpecIsUnchanged", required = false, defaultValue = "false")
@Parameter(name = "skipIfSpecIsUnchanged", property = "codegen.skipIfSpecIsUnchanged", defaultValue = "false")
private Boolean skipIfSpecIsUnchanged;
/**
* Add the output directory to the project as a source root, so that the generated java types
* are compiled and included in the project artifact.
*/
@Parameter(defaultValue = "true")
@Parameter(defaultValue = "true", property = "openapi.generator.maven.plugin.addCompileSourceRoot")
private boolean addCompileSourceRoot = true;
@Parameter
protected Map<String, String> environmentVariables = new HashMap<String, String>();
protected Map<String, String> environmentVariables = new HashMap<>();
@Parameter
protected Map<String, String> originalEnvironmentVariables = new HashMap<String, String>();
protected Map<String, String> originalEnvironmentVariables = new HashMap<>();
@Parameter(property = "codegen.configHelp")
private boolean configHelp = false;
@ -425,36 +433,36 @@ public class CodeGenMojo extends AbstractMojo {
addCompileSourceRootIfConfigured();
try {
if (skip) {
if (Boolean.TRUE.equals(skip)) {
getLog().info("Code generation is skipped.");
return;
}
if (buildContext != null) {
if (buildContext.isIncremental()) {
if (inputSpec != null) {
if (inputSpecFile.exists()) {
if (!buildContext.hasDelta(inputSpecFile)) {
getLog().info(
"Code generation is skipped in delta-build because source-json was not modified.");
return;
}
}
}
if (buildContext != null && inputSpec != null ) {
if (buildContext.isIncremental() &&
inputSpecFile.exists() &&
!buildContext.hasDelta(inputSpecFile)) {
getLog().info(
"Code generation is skipped in delta-build because source-json was not modified.");
return;
}
}
if (skipIfSpecIsUnchanged) {
if (inputSpecFile.exists()) {
File storedInputSpecHashFile = getHashFile(inputSpecFile);
if(storedInputSpecHashFile.exists()) {
String inputSpecHash = calculateInputSpecHash(inputSpecFile);
String storedInputSpecHash = Files.asCharSource(storedInputSpecHashFile, Charsets.UTF_8).read();
if (inputSpecHash.equals(storedInputSpecHash)) {
getLog().info(
"Code generation is skipped because input was unchanged");
return;
}
if (Boolean.TRUE.equals(skipIfSpecIsUnchanged) && inputSpecFile.exists()) {
File storedInputSpecHashFile = getHashFile(inputSpecFile);
if (storedInputSpecHashFile.exists()) {
String inputSpecHash = null;
try {
inputSpecHash = calculateInputSpecHash(inputSpecFile);
} catch (IOException ex) {
ex.printStackTrace();
}
@SuppressWarnings("UnstableApiUsage")
String storedInputSpecHash = Files.asCharSource(storedInputSpecHashFile, StandardCharsets.UTF_8).read();
if (storedInputSpecHash.equals(inputSpecHash)) {
getLog().info(
"Code generation is skipped because input was unchanged");
return;
}
}
}
@ -603,7 +611,7 @@ public class CodeGenMojo extends AbstractMojo {
// Set generation options
if (null != generateApis && generateApis) {
GlobalSettings.setProperty(CodegenConstants.APIS, "");
GlobalSettings.setProperty(CodegenConstants.APIS, apisToGenerate);
} else {
GlobalSettings.clearProperty(CodegenConstants.APIS);
}
@ -703,16 +711,12 @@ public class CodeGenMojo extends AbstractMojo {
}
if (environmentVariables != null) {
for (String key : environmentVariables.keySet()) {
originalEnvironmentVariables.put(key, GlobalSettings.getProperty(key));
String value = environmentVariables.get(key);
if (value == null) {
// don't put null values
value = "";
if (value != null) {
configurator.addSystemProperty(key, value);
}
GlobalSettings.setProperty(key, value);
configurator.addSystemProperty(key, value);
}
}
@ -752,14 +756,14 @@ public class CodeGenMojo extends AbstractMojo {
File parent = new File(storedInputSpecHashFile.getParent());
parent.mkdirs();
}
Files.asCharSink(storedInputSpecHashFile, Charsets.UTF_8).write(inputSpecHash);
Files.asCharSink(storedInputSpecHashFile, StandardCharsets.UTF_8).write(inputSpecHash);
} catch (Exception e) {
// Maven logs exceptions thrown by plugins only if invoked with -e
// I find it annoying to jump through hoops to get basic diagnostic information,
// so let's log it in any case:
if (buildContext != null) {
buildContext.addError(inputSpecFile, 0, 0, "unexpected error in Open-API generation", e);
buildContext.addMessage(inputSpecFile, 0, 0, "unexpected error in Open-API generation", BuildContext.SEVERITY_WARNING, e);
}
getLog().error(e);
throw new MojoExecutionException(
@ -787,8 +791,8 @@ public class CodeGenMojo extends AbstractMojo {
URLConnection conn = inputSpecRemoteUrl.openConnection();
if (isNotEmpty(auth)) {
List<AuthorizationValue> authList = AuthParser.parse(auth);
for (AuthorizationValue auth : authList) {
conn.setRequestProperty(auth.getKeyName(), auth.getValue());
for (AuthorizationValue a : authList) {
conn.setRequestProperty(a.getKeyName(), a.getValue());
}
}
try (ReadableByteChannel readableByteChannel = Channels.newChannel(conn.getInputStream())) {
@ -804,7 +808,7 @@ public class CodeGenMojo extends AbstractMojo {
inputSpecTempFile.exists()
? Files.asByteSource(inputSpecTempFile)
: CharSource.wrap(ClasspathHelper.loadFileFromClasspath(inputSpecTempFile.toString().replaceAll("\\\\","/")))
.asByteSource(Charsets.UTF_8);
.asByteSource(StandardCharsets.UTF_8);
return inputSpecByteSource.hash(Hashing.sha256()).toString();
}