mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2025-12-04 06:56:15 +00:00
Compare commits
1 Commits
dart-oneof
...
document-e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e52cd1a51e |
6
.github/ISSUE_TEMPLATE/bug_report.md
vendored
6
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -11,10 +11,10 @@ assignees: ''
|
||||
|
||||
- [ ] Have you provided a full/minimal spec to reproduce the issue?
|
||||
- [ ] Have you validated the input using an OpenAPI validator ([example](https://apidevtools.org/swagger-parser/online/))?
|
||||
- [ ] Have you [tested with the latest master](https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-to-test-with-the-latest-master-of-openapi-generator) to confirm the issue still exists?
|
||||
- [ ] Have you searched for related issues/PRs?
|
||||
- [ ] What's the version of OpenAPI Generator used?
|
||||
- [ ] Have you search for related issues/PRs?
|
||||
- [ ] What's the actual output vs expected output?
|
||||
- [ ] [Optional] Sponsorship to speed up the bug fix or feature request ([example](https://github.com/OpenAPITools/openapi-generator/issues/6178))
|
||||
- [ ] [Optional] Bounty to sponsor the fix ([example](https://www.bountysource.com/issues/66123212-javascript-client-produces-a-wrong-object-for-a-string-enum-type-that-is-used-with-ref))
|
||||
|
||||
<!--
|
||||
Please follow the issue template below for bug reports.
|
||||
|
||||
9
.github/workflows/sonar.yml
vendored
9
.github/workflows/sonar.yml
vendored
@@ -4,7 +4,6 @@ on:
|
||||
branches:
|
||||
- master
|
||||
- '[4-9]+.[0-9]+.x'
|
||||
- sonar
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -13,13 +12,13 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Set up JDK 11
|
||||
- name: Set up JDK 1.8
|
||||
uses: actions/setup-java@v1
|
||||
with:
|
||||
java-version: 11
|
||||
java-version: 1.8
|
||||
- name: Compile with Maven
|
||||
run: mvn -B -q clean install jacoco:report
|
||||
run: mvn clean package jacoco:report
|
||||
- name: Jacoco Aggregate
|
||||
run: mvn jacoco:report-aggregate
|
||||
- name: Publish to Sonar
|
||||
run: mvn -B -q -nsu sonar:sonar -Dsonar.projectKey=OpenAPITools_openapi-generator -Dsonar.organization=openapitools -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_LOGIN }} -Dsonar.branch.name=${GITHUB_REF##*/}
|
||||
run: mvn -B -q sonar:sonar -Dsonar.projectKey=OpenAPITools_openapi-generator -Dsonar.organization=openapitools -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_LOGIN }} -Dsonar.branch.name=${GITHUB_REF##*/}
|
||||
|
||||
19
README.md
19
README.md
@@ -103,8 +103,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
|
||||
| OpenAPI Generator Version | Release Date | Notes |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- |
|
||||
| 5.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/) | TBD | Major release with breaking changes (no fallback) |
|
||||
| 5.0.0-beta3 (upcoming beta release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/) | 01.11.2020 | Major beta release with breaking changes (no fallback) |
|
||||
| [5.0.0-beta2](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0-beta2) (latest beta release) | 04.09.2020 | Major beta release with breaking changes (no fallback) |
|
||||
| 5.0.0-beta2 (upcoming beta release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/) | 30.07.2020 | Major beta release with breaking changes (no fallback) |
|
||||
| [5.0.0-beta](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0-beta) (latest beta release) | 30.06.2020 | Major beta release with breaking changes (no fallback) |
|
||||
| [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) (latest stable release) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) |
|
||||
|
||||
@@ -162,16 +161,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository.
|
||||
<!-- RELEASE_VERSION -->
|
||||
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum):
|
||||
|
||||
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar`
|
||||
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar`
|
||||
|
||||
For **Mac/Linux** users:
|
||||
```sh
|
||||
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar -O openapi-generator-cli.jar
|
||||
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar -O openapi-generator-cli.jar
|
||||
```
|
||||
|
||||
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
|
||||
```
|
||||
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar
|
||||
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar
|
||||
```
|
||||
|
||||
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
|
||||
@@ -393,10 +392,10 @@ openapi-generator version
|
||||
```
|
||||
|
||||
<!-- RELEASE_VERSION -->
|
||||
Or install a particular OpenAPI Generator version (e.g. v5.0.0-beta2):
|
||||
Or install a particular OpenAPI Generator version (e.g. v5.0.0-beta):
|
||||
|
||||
```sh
|
||||
npm install @openapitools/openapi-generator-cli@cli-5.0.0-beta2 -g
|
||||
npm install @openapitools/openapi-generator-cli@cli-5.0.0-beta -g
|
||||
```
|
||||
|
||||
Or install it as dev-dependency:
|
||||
@@ -420,7 +419,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
|
||||
(if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g php -o c:\temp\php_api_client`)
|
||||
|
||||
<!-- RELEASE_VERSION -->
|
||||
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar)
|
||||
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar)
|
||||
<!-- /RELEASE_VERSION -->
|
||||
|
||||
To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate`
|
||||
@@ -771,12 +770,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
|
||||
- 2020-07-20 - [Datadog API client libraries now available for Java and Go](https://www.datadoghq.com/blog/java-go-libraries/) by Jordan Obey at [Datadog Blog](https://www.datadoghq.com/blog)
|
||||
- 2020-07-23 - [Generate Client SDK for .NET Core using Open Api](https://dev.to/no0law1/generate-client-sdk-for-net-core-using-open-api-2dgh) by [Nuno Reis](https://dev.to/no0law1)
|
||||
- 2020-07-26 - [Dartのhttp_interceptorライブラリを使うと配列のクエリパラメータが消えてしまう件の応急処置](https://qiita.com/gyamoto/items/eeeff81b6770487319ed) by [@gyamoto](https://qiita.com/gyamoto)
|
||||
- 2020-08-01 - [Generate Angular ReactiveForms from Swagger/OpenAPI](https://dev.to/martinmcwhorter/generate-angular-reactiveforms-from-swagger-openapi-35h9) by [Martin McWhorter](https://dev.to/martinmcwhorter)
|
||||
- 2020-08-03 - [Criando Bibliotecas para APIs RESTful com OpenAPI, Swagger Editor e OpenAPI Generator](https://medium.com/@everisBrasil/criando-bibliotecas-para-apis-restful-com-openapi-swagger-editor-e-openapi-generator-75349a6420fd) by [everis Brasil (an NTT DATA Company)](https://medium.com/@everisBrasil)
|
||||
- 2020-08-19 - [マイクロサービスを連携してみよう](https://thinkit.co.jp/article/17704) by [岡井 裕矢(おかい ゆうや)](https://thinkit.co.jp/author/17588), [泉 勝(いずみ まさる)](https://thinkit.co.jp/author/17705) at [Think IT(シンクイット)](https://thinkit.co.jp/)
|
||||
- 2020-08-25 - [OpenAPI Generator と TypeScript で型安全にフロントエンド開発をしている話](https://tech.smarthr.jp/entry/2020/08/25/135631) at [SmartHR Tech Blog](https://tech.smarthr.jp/)
|
||||
- 2020-09-10 - [Introduction to OpenAPI with Instana](https://www.instana.com/blog/introduction-to-openapi-with-instana/) by [Cedric Ziel](https://www.instana.com/blog/author/cedricziel/) at [Instana Blog](https://www.instana.com/blog/)
|
||||
- 2020-09-17 - [Generate PowerShellSDK using openapi-generator](https://medium.com/@ghufz.learn/generate-powershellsdk-using-openapi-generator-33b700891e33) by [Ghufran Zahidi](https://medium.com/@ghufz.learn)
|
||||
|
||||
## [6 - About Us](#table-of-contents)
|
||||
|
||||
|
||||
@@ -4,5 +4,4 @@ inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-e
|
||||
templateDir: modules/openapi-generator/src/main/resources/csharp-netcore
|
||||
additionalProperties:
|
||||
packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'
|
||||
useCompareNetObjects: true
|
||||
disallowAdditionalPropertiesIfNotPresent: false
|
||||
useCompareNetObjects: "true"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
generatorName: dart
|
||||
outputDir: samples/client/petstore/dart2/petstore_client_lib
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/dart/petstore.yaml
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/dart2
|
||||
additionalProperties:
|
||||
hideGenerationTimestamp: "true"
|
||||
|
||||
6
bin/configs/go-experimental-go-petstore-oas2.yaml
Normal file
6
bin/configs/go-experimental-go-petstore-oas2.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
generatorName: go-experimental
|
||||
outputDir: samples/client/petstore/go-experimental/go-petstore
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/go-experimental
|
||||
additionalProperties:
|
||||
packageName: petstore
|
||||
8
bin/configs/go-experimental-go-petstore.yaml
Normal file
8
bin/configs/go-experimental-go-petstore.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
generatorName: go-experimental
|
||||
outputDir: samples/openapi3/client/petstore/go-experimental/go-petstore
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/go-experimental
|
||||
additionalProperties:
|
||||
enumClassPrefix: "true"
|
||||
packageName: petstore
|
||||
disallowAdditionalPropertiesIfNotPresent: false
|
||||
@@ -1,6 +0,0 @@
|
||||
generatorName: go
|
||||
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/go-experimental
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/go
|
||||
additionalProperties:
|
||||
packageName: x_auth_id_alias
|
||||
@@ -4,4 +4,3 @@ inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-e
|
||||
templateDir: modules/openapi-generator/src/main/resources/go
|
||||
additionalProperties:
|
||||
packageName: petstore
|
||||
generateInterfaces: true
|
||||
|
||||
8
bin/configs/go-petstore-withXml.yaml
Normal file
8
bin/configs/go-petstore-withXml.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
generatorName: go
|
||||
outputDir: samples/client/petstore/go/go-petstore-withXml
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/go
|
||||
additionalProperties:
|
||||
packageName: petstore
|
||||
withXml: "true"
|
||||
withGoCodegenComment: "true"
|
||||
@@ -1,9 +1,7 @@
|
||||
generatorName: go
|
||||
outputDir: samples/openapi3/client/petstore/go/go-petstore
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/go
|
||||
additionalProperties:
|
||||
enumClassPrefix: "true"
|
||||
packageName: petstore
|
||||
disallowAdditionalPropertiesIfNotPresent: false
|
||||
generateInterfaces: true
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
generatorName: java
|
||||
outputDir: samples/client/petstore/java/feign-no-nullable
|
||||
library: feign
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/Java
|
||||
additionalProperties:
|
||||
booleanGetterPrefix: is
|
||||
artifactId: petstore-feign-no-nullable
|
||||
hideGenerationTimestamp: "true"
|
||||
additionalModelTypeAnnotations: '@javax.annotation.concurrent.Immutable'
|
||||
openApiNullable: "false"
|
||||
@@ -1,7 +0,0 @@
|
||||
generatorName: java
|
||||
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8
|
||||
library: jersey2
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml
|
||||
additionalProperties:
|
||||
artifactId: openapi3-extensions-x-auth-id-alias-jersey2-java8
|
||||
hideGenerationTimestamp: true
|
||||
@@ -1,7 +0,0 @@
|
||||
generatorName: java-play-framework
|
||||
outputDir: samples/server/petstore/java-play-framework-no-nullable
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/JavaPlayFramework
|
||||
additionalProperties:
|
||||
hideGenerationTimestamp: "true"
|
||||
openApiNullable: "false"
|
||||
@@ -1,9 +0,0 @@
|
||||
generatorName: java
|
||||
outputDir: samples/client/petstore/java/vertx-no-nullable
|
||||
library: vertx
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/Java
|
||||
additionalProperties:
|
||||
artifactId: petstore-vertx-no-nullable
|
||||
hideGenerationTimestamp: "true"
|
||||
openApiNullable: "false"
|
||||
@@ -1,7 +1,7 @@
|
||||
generatorName: java-vertx-web
|
||||
outputDir: samples/server/petstore/java-vertx-web
|
||||
outputDir: samples/server/petstore/java-vertx-web/rx
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/JavaVertXWebServer
|
||||
additionalProperties:
|
||||
hideGenerationTimestamp: "true"
|
||||
artifactId: java-vertx-web-server
|
||||
artifactId: java-vertx-web-rx-server
|
||||
@@ -4,5 +4,5 @@ library: reqwest
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/rust
|
||||
additionalProperties:
|
||||
supportAsync: false
|
||||
supportAsync: "false"
|
||||
packageName: petstore-reqwest
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
generatorName: spring
|
||||
outputDir: samples/server/petstore/springboot-beanvalidation-no-nullable
|
||||
library: spring-boot
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
|
||||
additionalProperties:
|
||||
java8: "false"
|
||||
useBeanValidation: true
|
||||
artifactId: spring-boot-beanvalidation-no-nullable
|
||||
hideGenerationTimestamp: "true"
|
||||
openApiNullable: "false"
|
||||
@@ -1,10 +0,0 @@
|
||||
generatorName: spring
|
||||
outputDir: samples/client/petstore/spring-cloud-no-nullable
|
||||
library: spring-cloud
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud
|
||||
additionalProperties:
|
||||
artifactId: petstore-spring-cloud-no-nullable
|
||||
responseWrapper: HystrixCommand
|
||||
hideGenerationTimestamp: "true"
|
||||
openApiNullable: "false"
|
||||
@@ -1,10 +0,0 @@
|
||||
generatorName: spring
|
||||
outputDir: samples/server/petstore/spring-mvc-no-nullable
|
||||
library: spring-mvc
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
|
||||
additionalProperties:
|
||||
artifactId: spring-mvc-server-no-nullable
|
||||
openApiNullable: "false"
|
||||
serverPort: "8002"
|
||||
hideGenerationTimestamp: "true"
|
||||
@@ -3,77 +3,6 @@ id: customization
|
||||
title: Customization
|
||||
---
|
||||
|
||||
## User-defined Templates
|
||||
|
||||
The most common scenario for user customization is to override the built-in templates with small modifications. That scenario's documentation is in our [templating](./templating.md) page, and differs from user-defined templates.
|
||||
|
||||
Prior to release 5.0.0, whenever a user wanted to include templates which weren't built-in or weren't known to the generator at compile time, they'd need to follow the more involved approach of creating a custom generator as documented later in this document. Beginning in 5.0.0, a user may now provide additional supporting files and extensions to built-in templates via configuration. This feature requires using the external configuration file feature.
|
||||
|
||||
Consider that you might want to add some static documentation such as `AUTHORS.md` and a custom tooling script. Rather than a single file for API definitions you also want an implementation file and a separate interface file for each.
|
||||
|
||||
You might have an external configuration file named `config.yaml` which defines additional properties like this for a `kotlin` client generator:
|
||||
|
||||
```yaml
|
||||
additionalProperties:
|
||||
artifactId: kotlin-petstore-client
|
||||
serializableModel: "true"
|
||||
dateLibrary: java8
|
||||
```
|
||||
|
||||
You would generate via CLI with the command:
|
||||
|
||||
```shell script
|
||||
openapi-generator generate -g kotlin -i spec.yaml -o outdir -c config.yaml
|
||||
```
|
||||
|
||||
To support the above scenario with custom templates, ensure that you're pointing to your custom template directory and add a `files` node with template file definitions to your config:
|
||||
|
||||
```
|
||||
templateDir: my_custom_templates
|
||||
additionalProperties:
|
||||
artifactId: kotlin-petstore-client
|
||||
serializableModel: "true"
|
||||
dateLibrary: java8
|
||||
files:
|
||||
AUTHORS.md: {}
|
||||
api_interfaces.mustache:
|
||||
templateType: API
|
||||
destinationFilename: Interface.kt
|
||||
api.mustache:
|
||||
templateType: API
|
||||
destinationFilename: Impl.kt
|
||||
other/check.mustache:
|
||||
folder: scripts
|
||||
destinationFilename: check.sh
|
||||
templateType: SupportingFiles
|
||||
```
|
||||
|
||||
The keys under the `files` node are your template filenames. These honor the same resolution order as all other templates.
|
||||
|
||||
The above configuration will do the following:
|
||||
|
||||
* Copy `my_custom_templates/AUTHORS.md` to the generated output directory without processing via the template engine (due to template file extension). The empty object definition following `AUTHORS.md` allows the tool to infer the target output filename in the root of the output directory.
|
||||
* Compile a user-provided `my_custom_templates/api_interfaces.mustache` following our usual API template compilation logic. That is, one file will be created per API; APIs are generated defined according to tags in your spec documentation. The destination filename of `Interface.kt` will act as a suffix for the filename. So, a tag of `Equipment` will output a corresponding `EquipmentInterface.kt`.
|
||||
* Because `api.mustache` is the same mustache filename as used in your target generator (`kotlin` in this example), we support the following:
|
||||
- The destination filename provides a suffix for the generated output. APIs generate per tag in your specification. So, a tag of `Equipment` will output a corresponding `EquipmentImpl.kt`. This option will be used whether `api.mustache` targets a user customized template or a built-in template.
|
||||
- The built-in template will be used if you haven't provided an customized template. The kotlin generator defines the suffix as simply `.kt`, so this scenario would modify only the generated file suffixes according to the previous bullet point.
|
||||
- Your `api.mustache` will be used if it exists in your custom template directory. For generators with library options, such as `jvm-okhttp3` in the kotlin generator, your file must exist in the same relative location as the embedded template. For kotlin using the `jvm-okhttp3` library option, this file would need to be located at `my_custom_templates/libraries/jvm-okhttp/api.mustache`. See [templating](./templating.md) for more details.
|
||||
* Compile `my_custom_templates/other/check.mustache` with the supporting files bundle, and output to `scripts/check.sh` in your output directory. Note that we don't currently support setting file flags on output, so scripts such as these will either have to be sourced rather than executed, or have file flags set separately after generation (external to our tooling).
|
||||
|
||||
The `templateType` option will default to `SupportingFiles`, so the option for `other/check.mustache` is redundant and provided to demonstrate the full template file configuration options. The available template types are:
|
||||
|
||||
* API
|
||||
* APIDocs
|
||||
* APITests
|
||||
* Model
|
||||
* ModelDocs
|
||||
* ModelTests
|
||||
* SupportingFiles
|
||||
|
||||
Excluding `SupportingFiles`, each of the above options may result in multiple files. API related types create a file per API. Model related types create a file for each model.
|
||||
|
||||
Note that user-defined templates will merge with built-in template definitions. If a supporting file with the sample template file path exists, it will be replaced with the user-defined template, otherwise the user-defined template will be added to the list of template files to compile. If the generator's built-in template is `model_docs.mustache` and you define `model-docs.mustache`, this will result in duplicated model docs (if `destinationFilename` differs) or undefined behavior as whichever template compiles last will overwrite the previous model docs (if `destinationFilename` matches the extension or suffix in the generator's code).
|
||||
|
||||
## Custom Generator (and Template)
|
||||
|
||||
<a id="creating-a-new-template"></a> If none of the built-in generators suit your needs and you need to do more than just modify the mustache templates to tweak generated code, you can create a brand new generator and its associated templates. OpenAPI Generator can help with this, using the `meta` command:
|
||||
@@ -91,12 +20,7 @@ These names can be anything you like. If you are building a client for the white
|
||||
|
||||
### Use your new generator with the CLI
|
||||
|
||||
To compile your library, enter the `out/generators/my-codegen` directory, run `mvn package`.
|
||||
|
||||
**NOTE** Running your custom generator requires adding it to the classpath. This differs on [Windows](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html) slightly from [unix](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html).
|
||||
If you are running a Windows Subsystem for Linux or a shell such as gitbash, and have issues with the unix variant, try the Windows syntax below.
|
||||
|
||||
Now, execute the generator:
|
||||
To compile your library, enter the `out/generators/my-codegen` directory, run `mvn package` and execute the generator:
|
||||
|
||||
```sh
|
||||
java -cp out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar:modules/openapi-generator-cli/target/openapi-generator-cli.jar org.openapitools.codegen.OpenAPIGenerator
|
||||
@@ -104,7 +28,7 @@ java -cp out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar
|
||||
|
||||
For Windows users, you will need to use `;` instead of `:` in the classpath, e.g.
|
||||
```
|
||||
java -cp "out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar" org.openapitools.codegen.OpenAPIGenerator
|
||||
java -cp out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar org.openapitools.codegen.OpenAPIGenerator
|
||||
```
|
||||
|
||||
Note the `my-codegen` is an option for `-g` now, and you can use the usual arguments for generating your code:
|
||||
@@ -118,7 +42,7 @@ java -cp out/codegens/customCodegen/target/my-codegen-openapi-generator-1.0.0.ja
|
||||
|
||||
For Windows users:
|
||||
```
|
||||
java -cp "out/codegens/customCodegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar" \
|
||||
java -cp out/codegens/customCodegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar \
|
||||
org.openapitools.codegen.OpenAPIGenerator generate -g my-codegen \
|
||||
-i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml \
|
||||
-o ./out/myClient
|
||||
|
||||
@@ -29,7 +29,7 @@ The following generators are available:
|
||||
* [erlang-proper](generators/erlang-proper.md)
|
||||
* [flash-deprecated (deprecated)](generators/flash-deprecated.md)
|
||||
* [go](generators/go.md)
|
||||
* [go-deprecated (deprecated)](generators/go-deprecated.md)
|
||||
* [go-experimental (experimental)](generators/go-experimental.md)
|
||||
* [groovy](generators/groovy.md)
|
||||
* [haskell-http-client](generators/haskell-http-client.md)
|
||||
* [java](generators/java.md)
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
---
|
||||
title: Config Options for go-deprecated
|
||||
sidebar_label: go-deprecated
|
||||
---
|
||||
|
||||
| Option | Description | Values | Default |
|
||||
| ------ | ----------- | ------ | ------- |
|
||||
|enumClassPrefix|Prefix enum with class name| |false|
|
||||
|generateInterfaces|Generate interfaces for api classes| |false|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|
||||
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|
||||
|packageName|Go package name (convention: lowercase).| |openapi|
|
||||
|packageVersion|Go package version.| |1.0.0|
|
||||
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|
||||
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts| |false|
|
||||
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|
||||
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
|
||||
| Type/Alias | Imports |
|
||||
| ---------- | ------- |
|
||||
|
||||
|
||||
## INSTANTIATION TYPES
|
||||
|
||||
| Type/Alias | Instantiated By |
|
||||
| ---------- | --------------- |
|
||||
|
||||
|
||||
## LANGUAGE PRIMITIVES
|
||||
|
||||
<ul class="column-ul">
|
||||
<li>bool</li>
|
||||
<li>byte</li>
|
||||
<li>complex128</li>
|
||||
<li>complex64</li>
|
||||
<li>float32</li>
|
||||
<li>float64</li>
|
||||
<li>int</li>
|
||||
<li>int32</li>
|
||||
<li>int64</li>
|
||||
<li>interface{}</li>
|
||||
<li>map[string]interface{}</li>
|
||||
<li>rune</li>
|
||||
<li>string</li>
|
||||
<li>uint</li>
|
||||
<li>uint32</li>
|
||||
<li>uint64</li>
|
||||
</ul>
|
||||
|
||||
## RESERVED WORDS
|
||||
|
||||
<ul class="column-ul">
|
||||
<li>bool</li>
|
||||
<li>break</li>
|
||||
<li>byte</li>
|
||||
<li>case</li>
|
||||
<li>chan</li>
|
||||
<li>complex128</li>
|
||||
<li>complex64</li>
|
||||
<li>const</li>
|
||||
<li>continue</li>
|
||||
<li>default</li>
|
||||
<li>defer</li>
|
||||
<li>else</li>
|
||||
<li>error</li>
|
||||
<li>fallthrough</li>
|
||||
<li>float32</li>
|
||||
<li>float64</li>
|
||||
<li>for</li>
|
||||
<li>func</li>
|
||||
<li>go</li>
|
||||
<li>goto</li>
|
||||
<li>if</li>
|
||||
<li>import</li>
|
||||
<li>int</li>
|
||||
<li>int16</li>
|
||||
<li>int32</li>
|
||||
<li>int64</li>
|
||||
<li>int8</li>
|
||||
<li>interface</li>
|
||||
<li>map</li>
|
||||
<li>nil</li>
|
||||
<li>package</li>
|
||||
<li>range</li>
|
||||
<li>return</li>
|
||||
<li>rune</li>
|
||||
<li>select</li>
|
||||
<li>string</li>
|
||||
<li>struct</li>
|
||||
<li>switch</li>
|
||||
<li>type</li>
|
||||
<li>uint</li>
|
||||
<li>uint16</li>
|
||||
<li>uint32</li>
|
||||
<li>uint64</li>
|
||||
<li>uint8</li>
|
||||
<li>uintptr</li>
|
||||
<li>var</li>
|
||||
</ul>
|
||||
|
||||
## FEATURE SET
|
||||
|
||||
|
||||
### Client Modification Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|BasePath|✓|ToolingExtension
|
||||
|Authorizations|✗|ToolingExtension
|
||||
|UserAgent|✓|ToolingExtension
|
||||
|MockServer|✗|ToolingExtension
|
||||
|
||||
### Data Type Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|Custom|✗|OAS2,OAS3
|
||||
|Int32|✓|OAS2,OAS3
|
||||
|Int64|✓|OAS2,OAS3
|
||||
|Float|✓|OAS2,OAS3
|
||||
|Double|✓|OAS2,OAS3
|
||||
|Decimal|✓|ToolingExtension
|
||||
|String|✓|OAS2,OAS3
|
||||
|Byte|✓|OAS2,OAS3
|
||||
|Binary|✓|OAS2,OAS3
|
||||
|Boolean|✓|OAS2,OAS3
|
||||
|Date|✓|OAS2,OAS3
|
||||
|DateTime|✓|OAS2,OAS3
|
||||
|Password|✓|OAS2,OAS3
|
||||
|File|✓|OAS2
|
||||
|Array|✓|OAS2,OAS3
|
||||
|Maps|✓|ToolingExtension
|
||||
|CollectionFormat|✓|OAS2
|
||||
|CollectionFormatMulti|✓|OAS2
|
||||
|Enum|✓|OAS2,OAS3
|
||||
|ArrayOfEnum|✓|ToolingExtension
|
||||
|ArrayOfModel|✓|ToolingExtension
|
||||
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|
||||
|ArrayOfCollectionOfModel|✓|ToolingExtension
|
||||
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|
||||
|MapOfEnum|✓|ToolingExtension
|
||||
|MapOfModel|✓|ToolingExtension
|
||||
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|
||||
|MapOfCollectionOfModel|✓|ToolingExtension
|
||||
|MapOfCollectionOfEnum|✓|ToolingExtension
|
||||
|
||||
### Documentation Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|Readme|✓|ToolingExtension
|
||||
|Model|✓|ToolingExtension
|
||||
|Api|✓|ToolingExtension
|
||||
|
||||
### Global Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|Host|✓|OAS2,OAS3
|
||||
|BasePath|✓|OAS2,OAS3
|
||||
|Info|✓|OAS2,OAS3
|
||||
|Schemes|✗|OAS2,OAS3
|
||||
|PartialSchemes|✓|OAS2,OAS3
|
||||
|Consumes|✓|OAS2
|
||||
|Produces|✓|OAS2
|
||||
|ExternalDocumentation|✓|OAS2,OAS3
|
||||
|Examples|✓|OAS2,OAS3
|
||||
|XMLStructureDefinitions|✗|OAS2,OAS3
|
||||
|MultiServer|✗|OAS3
|
||||
|ParameterizedServer|✓|OAS3
|
||||
|ParameterStyling|✗|OAS3
|
||||
|Callbacks|✗|OAS3
|
||||
|LinkObjects|✗|OAS3
|
||||
|
||||
### Parameter Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|Path|✓|OAS2,OAS3
|
||||
|Query|✓|OAS2,OAS3
|
||||
|Header|✓|OAS2,OAS3
|
||||
|Body|✓|OAS2
|
||||
|FormUnencoded|✓|OAS2
|
||||
|FormMultipart|✓|OAS2
|
||||
|Cookie|✓|OAS3
|
||||
|
||||
### Schema Support Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|Simple|✓|OAS2,OAS3
|
||||
|Composite|✓|OAS2,OAS3
|
||||
|Polymorphism|✗|OAS2,OAS3
|
||||
|Union|✗|OAS3
|
||||
|
||||
### Security Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|BasicAuth|✓|OAS2,OAS3
|
||||
|ApiKey|✓|OAS2,OAS3
|
||||
|OpenIDConnect|✗|OAS3
|
||||
|BearerToken|✗|OAS3
|
||||
|OAuth2_Implicit|✓|OAS2,OAS3
|
||||
|OAuth2_Password|✗|OAS2,OAS3
|
||||
|OAuth2_ClientCredentials|✗|OAS2,OAS3
|
||||
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
|
||||
|
||||
### Wire Format Feature
|
||||
| Name | Supported | Defined By |
|
||||
| ---- | --------- | ---------- |
|
||||
|JSON|✓|OAS2,OAS3
|
||||
|XML|✓|OAS2,OAS3
|
||||
|PROTOBUF|✗|ToolingExtension
|
||||
|Custom|✗|OAS2,OAS3
|
||||
@@ -7,7 +7,6 @@ sidebar_label: go-experimental
|
||||
| ------ | ----------- | ------ | ------- |
|
||||
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|
||||
|enumClassPrefix|Prefix enum with class name| |false|
|
||||
|generateInterfaces|Generate interfaces for api classes| |false|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|
||||
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|
||||
|packageName|Go package name (convention: lowercase).| |openapi|
|
||||
|
||||
@@ -5,17 +5,15 @@ sidebar_label: go
|
||||
|
||||
| Option | Description | Values | Default |
|
||||
| ------ | ----------- | ------ | ------- |
|
||||
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|
||||
|enumClassPrefix|Prefix enum with class name| |false|
|
||||
|generateInterfaces|Generate interfaces for api classes| |false|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|
||||
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|
||||
|packageName|Go package name (convention: lowercase).| |openapi|
|
||||
|packageVersion|Go package version.| |1.0.0|
|
||||
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|
||||
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts| |false|
|
||||
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |false|
|
||||
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|
||||
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
|
||||
@@ -24,14 +24,12 @@ sidebar_label: groovy
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -26,14 +26,12 @@ sidebar_label: java-inflector
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.controllers|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -26,7 +26,6 @@ sidebar_label: java-msf4j
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
@@ -35,7 +34,6 @@ sidebar_label: java-msf4j
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
@@ -51,7 +49,6 @@ sidebar_label: java-msf4j
|
||||
|sourceFolder|source folder for generated code| |src/main/java|
|
||||
|title|a title describing the application| |OpenAPI Server|
|
||||
|useBeanValidation|Use BeanValidation API annotations| |true|
|
||||
|useTags|use tags for creating interface and controller classnames| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
|
||||
@@ -28,14 +28,12 @@ sidebar_label: java-pkmst
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |com.prokarma|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |com.prokarma.pkmst.controller|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |com.prokarma.pkmst.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -30,14 +30,12 @@ sidebar_label: java-play-framework
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|handleExceptions|Add a 'throw exception' to each controller function. Add also a custom error handler where you can put your custom logic| |true|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |apimodels|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -26,14 +26,12 @@ sidebar_label: java-undertow-server
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.handler|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |null|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -26,14 +26,12 @@ sidebar_label: java-vertx-web
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.vertxweb.server|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.vertxweb.server.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -26,14 +26,12 @@ sidebar_label: java-vertx
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.server.api.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -28,7 +28,6 @@ sidebar_label: java
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.client|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
@@ -37,7 +36,6 @@ sidebar_label: java
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|microprofileFramework|Framework for microprofile. Possible values "kumuluzee"| |null|
|
||||
|modelPackage|package for generated models| |org.openapitools.client.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parcelableModel|Whether to generate models for Android that implement Parcelable with the okhttp-gson library.| |false|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -28,7 +28,6 @@ sidebar_label: jaxrs-cxf-cdi
|
||||
|generatePom|Whether to generate pom.xml if the file does not already exist.| |true|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
@@ -38,7 +37,6 @@ sidebar_label: jaxrs-cxf-cdi
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|openApiSpecFileLocation|Location where the file containing the spec will be generated in the output folder. No file generated when set to null or empty string.| |null|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
@@ -57,7 +55,6 @@ sidebar_label: jaxrs-cxf-cdi
|
||||
|title|a title describing the application| |OpenAPI Server|
|
||||
|useBeanValidation|Use BeanValidation API annotations| |true|
|
||||
|useSwaggerAnnotations|Whether to generate Swagger annotations.| |true|
|
||||
|useTags|use tags for creating interface and controller classnames| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
|
||||
@@ -26,14 +26,12 @@ sidebar_label: jaxrs-cxf-client
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -32,7 +32,6 @@ sidebar_label: jaxrs-cxf-extended
|
||||
|generateSpringBootApplication|Generate Spring Boot application| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
@@ -41,7 +40,6 @@ sidebar_label: jaxrs-cxf-extended
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|loadTestDataFromFile|Load test data from a generated JSON file| |false|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
@@ -71,7 +69,6 @@ sidebar_label: jaxrs-cxf-extended
|
||||
|useSpringAnnotationConfig|Use Spring Annotation Config| |false|
|
||||
|useSwaggerFeature|Use Swagger Feature| |false|
|
||||
|useSwaggerUI|Use Swagger UI| |false|
|
||||
|useTags|use tags for creating interface and controller classnames| |true|
|
||||
|useWadlFeature|Use WADL Feature| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ sidebar_label: jaxrs-cxf
|
||||
|generateSpringBootApplication|Generate Spring Boot application| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
@@ -39,7 +38,6 @@ sidebar_label: jaxrs-cxf
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
@@ -66,7 +64,6 @@ sidebar_label: jaxrs-cxf
|
||||
|useSpringAnnotationConfig|Use Spring Annotation Config| |false|
|
||||
|useSwaggerFeature|Use Swagger Feature| |false|
|
||||
|useSwaggerUI|Use Swagger UI| |false|
|
||||
|useTags|use tags for creating interface and controller classnames| |true|
|
||||
|useWadlFeature|Use WADL Feature| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ sidebar_label: jaxrs-jersey
|
||||
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
@@ -35,7 +34,6 @@ sidebar_label: jaxrs-jersey
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -27,7 +27,6 @@ sidebar_label: jaxrs-resteasy-eap
|
||||
|generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |true|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
@@ -35,7 +34,6 @@ sidebar_label: jaxrs-resteasy-eap
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
@@ -52,7 +50,6 @@ sidebar_label: jaxrs-resteasy-eap
|
||||
|title|a title describing the application| |OpenAPI Server|
|
||||
|useBeanValidation|Use BeanValidation API annotations| |true|
|
||||
|useSwaggerFeature|Use dynamic Swagger generator| |false|
|
||||
|useTags|use tags for creating interface and controller classnames| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
|
||||
@@ -27,7 +27,6 @@ sidebar_label: jaxrs-resteasy
|
||||
|generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |false|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
@@ -35,7 +34,6 @@ sidebar_label: jaxrs-resteasy
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
@@ -51,7 +49,6 @@ sidebar_label: jaxrs-resteasy
|
||||
|sourceFolder|source folder for generated code| |src/main/java|
|
||||
|title|a title describing the application| |OpenAPI Server|
|
||||
|useBeanValidation|Use BeanValidation API annotations| |true|
|
||||
|useTags|use tags for creating interface and controller classnames| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
|
||||
@@ -28,7 +28,6 @@ sidebar_label: jaxrs-spec
|
||||
|generatePom|Whether to generate pom.xml if the file does not already exist.| |true|
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implFolder|folder for generated implementation code| |src/main/java|
|
||||
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
@@ -38,7 +37,6 @@ sidebar_label: jaxrs-spec
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|openApiSpecFileLocation|Location where the file containing the spec will be generated in the output folder. No file generated when set to null or empty string.| |null|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
@@ -57,7 +55,6 @@ sidebar_label: jaxrs-spec
|
||||
|title|a title describing the application| |OpenAPI Server|
|
||||
|useBeanValidation|Use BeanValidation API annotations| |true|
|
||||
|useSwaggerAnnotations|Whether to generate Swagger annotations.| |true|
|
||||
|useTags|use tags for creating interface and controller classnames| |false|
|
||||
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
|
||||
@@ -9,7 +9,6 @@ sidebar_label: openapi
|
||||
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|
||||
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|outputFileName|Output file name| |openapi.json|
|
||||
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|
||||
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|
||||
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|
||||
|
||||
@@ -32,17 +32,15 @@ sidebar_label: spring
|
||||
|groupId|groupId in generated pom.xml| |org.openapitools|
|
||||
|hateoas|Use Spring HATEOAS library to allow adding HATEOAS links| |false|
|
||||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|
||||
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|
||||
|implicitHeaders|Skip header parameters in the generated API methods using @ApiImplicitParams annotation.| |false|
|
||||
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|
||||
|invokerPackage|root package for generated code| |org.openapitools.api|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used. IMPORTANT: This option has been deprecated as Java 8 is the default.</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|
||||
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|
||||
|library|library template (sub-template)|<dl><dt>**spring-boot**</dt><dd>Spring-boot Server application using the SpringFox integration.</dd><dt>**spring-mvc**</dt><dd>Spring-MVC Server application using the SpringFox integration.</dd><dt>**spring-cloud**</dt><dd>Spring-Cloud-Feign client with Spring-Boot auto-configured settings.</dd></dl>|spring-boot|
|
||||
|licenseName|The name of the license| |Unlicense|
|
||||
|licenseUrl|The URL of the license| |http://unlicense.org|
|
||||
|modelPackage|package for generated models| |org.openapitools.model|
|
||||
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|
||||
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|
||||
|
||||
@@ -23,7 +23,7 @@ The minimum set of files required to create a new generator are:
|
||||
- Should include a README explaining usage
|
||||
- Must include an `api.mustache`
|
||||
- Exists under `modules/openapi-generator/src/main/resources/` (plus `embeddedTemplate` dir value, see below)
|
||||
* Config file under `./bin/configs`
|
||||
* Sample scripts under `./bin`
|
||||
- Gives users a "real life" example of generated output
|
||||
- Samples are used by CI to verify generators and test for regressions in some cases
|
||||
|
||||
@@ -43,8 +43,6 @@ Usage:
|
||||
-c Create a client generator
|
||||
-s Create a server generator
|
||||
-d Create a documentation generator
|
||||
-H Create a schema generator
|
||||
-f Create a config generator
|
||||
-t When specified, creates test file(s) for the generator.
|
||||
-h Display help.
|
||||
|
||||
@@ -57,7 +55,8 @@ Examples:
|
||||
modules/openapi-generator/src/main/resources/kotlin-server/README.mustache
|
||||
modules/openapi-generator/src/main/resources/kotlin-server/model.mustache
|
||||
modules/openapi-generator/src/main/resources/kotlin-server/api.mustache
|
||||
bin/configs/kotlin-server-petstore-new.yaml
|
||||
bin/windows/kotlin-server-petstore.bat
|
||||
bin/kotlin-server-petstore.sh
|
||||
|
||||
Create a generic C# server generator:
|
||||
./new.sh -n csharp -s -t
|
||||
@@ -66,7 +65,8 @@ Examples:
|
||||
modules/openapi-generator/src/main/resources/csharp-server/README.mustache
|
||||
modules/openapi-generator/src/main/resources/csharp-server/model.mustache
|
||||
modules/openapi-generator/src/main/resources/csharp-server/api.mustache
|
||||
bin/configs/csharp-server-petstore-new.yaml
|
||||
bin/windows/csharp-server-petstore.bat
|
||||
bin/csharp-server-petstore.sh
|
||||
modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CsharpServerCodegenTest.java
|
||||
modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CsharpServerCodegenModelTest.java
|
||||
modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CsharpServerCodegenOptionsTest.java
|
||||
@@ -88,7 +88,8 @@ Creating modules/openapi-generator/src/main/java/org/openapitools/codegen/langua
|
||||
Creating modules/openapi-generator/src/main/resources/common-mark-documentation/README.mustache
|
||||
Creating modules/openapi-generator/src/main/resources/common-mark-documentation/model.mustache
|
||||
Creating modules/openapi-generator/src/main/resources/common-mark-documentation/api.mustache
|
||||
Creating bin/configs/common-mark-documentation-petstore-new.yaml
|
||||
Creating bin/windows/common-mark-documentation-petstore.bat
|
||||
Creating bin/common-mark-documentation-petstore.sh
|
||||
Finished.
|
||||
```
|
||||
|
||||
@@ -150,7 +151,7 @@ The `templateDir` variable refers to the "current" template directory setting, a
|
||||
Both of these variables exist because the generator will fallback to files under `embeddedTemplateDir` if they are not defined in the user's custom template directory.
|
||||
|
||||
```java
|
||||
apiPackage = "Apis";
|
||||
apiPackage = File.separator + "Apis";
|
||||
```
|
||||
|
||||
This sets the "package" location for anything considered an API document. You might want to change this setting if, for instance, your language doesn't support uppercase letters in the path. We don't need to worry about that here.
|
||||
@@ -158,7 +159,7 @@ This sets the "package" location for anything considered an API document. You mi
|
||||
Every templated output from `api.mustache` (registered via `apiTemplateFiles` above) will end up in the directory defined by `apiPackage` here.
|
||||
|
||||
```java
|
||||
modelPackage = "Models";
|
||||
modelPackage = File.separator + "Models";
|
||||
```
|
||||
|
||||
Similarly, this sets the package for `Models`.
|
||||
@@ -329,29 +330,61 @@ To compile quickly to test this out, you can run `mvn clean package -DskipTests`
|
||||
|
||||
### Compile Sample
|
||||
|
||||
The `new.sh` script created the generation config file `bin/configs/common-mark-documentation-petstore-new.yaml`:
|
||||
The `new.sh` script created `bin/common-mark-documentation-petstore.sh`:
|
||||
|
||||
```bash
|
||||
generatorName: common-mark
|
||||
outputDir: samples/documentation/petstore/common/mark
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/common-mark
|
||||
additionalProperties:
|
||||
hideGenerationTimestamp: "true"
|
||||
#!/bin/sh
|
||||
|
||||
SCRIPT="$0"
|
||||
|
||||
while [ -h "$SCRIPT" ] ; do
|
||||
ls=$(ls -ld "$SCRIPT")
|
||||
link=$(expr "$ls" : '.*-> \(.*\)$')
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
SCRIPT="$link"
|
||||
else
|
||||
SCRIPT=$(dirname "$SCRIPT")/"$link"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=$(dirname "$SCRIPT")/..
|
||||
APP_DIR=$(cd "${APP_DIR}"; pwd)
|
||||
fi
|
||||
|
||||
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
mvn clean package
|
||||
fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common/mark"
|
||||
|
||||
java ${JAVA_OPTS} -jar ${executable} ${ags}
|
||||
```
|
||||
|
||||
This configuration file is passed to the generator's CLI tool during continuous integration builds, and many outputs are compiled and tested as a regression test on every build. Contributors are also asked to run `./bin/utils/ensure-up-to-date` before opening a pull request to regenerate all samples defined under `./bin/configs`. This allows maintainers to quickly verify whether changes impact other generators.
|
||||
This script is often used to apply default options for generation. A common option in most of these script is to define the template directory as the generator's directory under `resources`. This allows template maintainers to modify and test out template changes which don't require recompilation of the entire project. You'd still need to recompile the project in full if you add or modify behaviors to the generator (such as adding a `CliOption`).
|
||||
|
||||
Configuration based examples allow us to test the same samples in each tooling option (CLI, Gradle Plugin, Maven Plugin, etc.).
|
||||
Add `-t modules/openapi-generator/src/main/resources/common-mark-documentation` to `ags` line to simplify the evaluation of template-only modifications:
|
||||
|
||||
You can compile your generator by running:
|
||||
```diff
|
||||
diff --git a/bin/markdown-documentation-petstore.sh b/bin/markdown-documentation-petstore.sh
|
||||
index d816771478..94b4ce6d12 100644
|
||||
--- a/bin/markdown-documentation-petstore.sh
|
||||
+++ b/bin/markdown-documentation-petstore.sh
|
||||
@@ -26,6 +26,6 @@ fi
|
||||
|
||||
```bash
|
||||
./bin/generate-samples.sh bin/configs/common-mark-documentation-petstore-new.yaml
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
-ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common-mark"
|
||||
+ags="$@ generate -t modules/openapi-generator/src/main/resources/common-mark-documentation -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common/markdown"
|
||||
|
||||
java ${JAVA_OPTS} -jar ${executable} ${ags}
|
||||
```
|
||||
|
||||
This configuration file can be used to demonstrate the default options for generation. A common option in most of these configs is to define the template directory as the generator's directory under `resources`. This allows template maintainers to modify and test out template changes which don't require recompilation of the entire project. You'd still need to recompile the project in full if you add or modify behaviors to the generator (such as adding a `CliOption`).
|
||||
|
||||
### Verify output
|
||||
|
||||
Creating a new generator will be an iterative task. Once you've generated the sample, you'll want to try it out. For compiled client/server outputs, this would mean running the code or creating a small sample project to consume your artifact just to make sure it works.
|
||||
|
||||
@@ -48,9 +48,7 @@ java -cp /path/totemplate-classpath-example-1.0-SNAPSHOT.jar:modules/openapi-gen
|
||||
-g html -o template-example -t templates/htmlDocs
|
||||
```
|
||||
|
||||
**NOTE** Running your custom generator in the example above requires adding it to the classpath. This differs on [Windows](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html) slightly from [unix](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html).
|
||||
|
||||
Take note that our template directory is relative to the resource directory of the JAR defined on the classpath.
|
||||
Note that our template directory is relative to the resource directory of the JAR defined on the classpath.
|
||||
|
||||
### Retrieving Templates
|
||||
|
||||
@@ -472,9 +470,7 @@ java $JAVA_OPTS -cp /your/path/build/libs/pebble-template-adapter-1.0-SNAPSHOT-a
|
||||
--global-property models,modelDocs,modelTests,apis,apiTests,apiDocs
|
||||
```
|
||||
|
||||
**NOTE** Running your custom generator requires adding it to the classpath. This differs on [Windows](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html) slightly from [unix](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html).
|
||||
|
||||
In the above example, we've targeted our custom template engine adapter via `-e pebble`. If you don't include the SPI file under `META-INF/services`, you'll need to specify the exact classpath: `org.openapitools.examples.templating.PebbleTemplateAdapter`. Notice that the target class here matches the Kotlin class name. This is because of the `@file:JvmName` annotation.
|
||||
Notice how we've targeted our custom template engine adapter via `-e pebble`. If you don't include the SPI file under `META-INF/services`, you'll need to specify the exact classpath: `org.openapitools.examples.templating.PebbleTemplateAdapter`. Notice that the target class here matches the Kotlin class name. This is because of the `@file:JvmName` annotation.
|
||||
|
||||
Congratulations on creating a custom templating engine adapter!
|
||||
|
||||
|
||||
@@ -602,7 +602,7 @@ openapi-generator generate -i petstore.yaml -g typescript-fetch -o out \
|
||||
The `batch` command allows you to move all CLI arguments supported by the `generate` command into a YAML or JSON file.
|
||||
|
||||
*NOTE*: This command supports an additional `!include` property which may point to another "shared" file, the base path to which can be
|
||||
modified by `--includes-base-dir`. Starting with 5.0.0, the `!batch` command supports multiple `!include` properties, either sequential or nested. In order to support multiple `!include` properties in a JSON file, the property name can have a suffix, e.g. `!include1`, `!include2`, etc. The suffix have no meaning other than providing unique property names.
|
||||
modified by `--includes-base-dir`.
|
||||
|
||||
```bash
|
||||
openapi-generator help batch
|
||||
|
||||
@@ -39,16 +39,15 @@ import java.util.stream.Collectors;
|
||||
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
|
||||
import static org.apache.commons.lang3.StringUtils.isEmpty;
|
||||
|
||||
@SuppressWarnings({"unused","java:S106", "java:S1192"})
|
||||
@SuppressWarnings({"unused","java:S106"})
|
||||
@Command(name = "config-help", description = "Config help for chosen lang")
|
||||
public class ConfigHelp extends OpenApiGeneratorCommand {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigHelp.class);
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Generate.class);
|
||||
|
||||
private static final String FORMAT_TEXT = "text";
|
||||
private static final String FORMAT_MARKDOWN = "markdown";
|
||||
private static final String FORMAT_YAMLSAMPLE = "yamlsample";
|
||||
private static final int FEATURE_SET_DISPLAY_WIDTH= 20;
|
||||
|
||||
@Option(name = {"-g",
|
||||
"--generator-name"}, title = "generator name", description = "generator to get config help for")
|
||||
@@ -148,7 +147,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
|
||||
LOGGER.error("[error] Check the spelling of the generator's name and try again.");
|
||||
System.exit(1);
|
||||
} catch (IOException e) {
|
||||
LOGGER.error("Unexpected error", e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,7 +396,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
|
||||
String definedByKey = "Defined By";
|
||||
int maxNameLength = flattened.stream().map(FeatureSet.FeatureSetFlattened::getFeatureName).mapToInt(String::length).max().orElse(nameKey.length());
|
||||
int maxSupportedLength = supportedKey.length();
|
||||
int definedInLength = FEATURE_SET_DISPLAY_WIDTH;
|
||||
int definedInLength = 20;
|
||||
String format = "%-" + maxNameLength + "s\t%-" + maxSupportedLength + "s\t%-" + definedInLength + "s";
|
||||
|
||||
flattened.forEach(featureSet -> {
|
||||
|
||||
@@ -18,19 +18,13 @@ package org.openapitools.codegen.cmd;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonToken;
|
||||
import com.fasterxml.jackson.core.TreeNode;
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
|
||||
import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.util.TokenBuffer;
|
||||
|
||||
import io.airlift.airline.Arguments;
|
||||
import io.airlift.airline.Command;
|
||||
import io.airlift.airline.Option;
|
||||
@@ -274,51 +268,35 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
|
||||
|
||||
@Override
|
||||
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
|
||||
TreeNode node = p.readValueAsTree();
|
||||
JsonNode include = (JsonNode) node.get(INCLUDE);
|
||||
ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();
|
||||
TokenBuffer buffer = new TokenBuffer(p);
|
||||
|
||||
recurse(buffer, p, codec, false);
|
||||
|
||||
JsonParser newParser = buffer.asParser(codec);
|
||||
newParser.nextToken();
|
||||
|
||||
return super.deserialize(newParser, ctx);
|
||||
}
|
||||
|
||||
private void recurse(TokenBuffer buffer, JsonParser p, ObjectMapper codec, boolean skipOuterbraces) throws IOException {
|
||||
boolean firstToken = true;
|
||||
JsonToken token;
|
||||
|
||||
while ((token = p.nextToken()) != null) {
|
||||
String name = p.currentName();
|
||||
|
||||
if (skipOuterbraces && firstToken && JsonToken.START_OBJECT.equals(token)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (skipOuterbraces && p.getParsingContext().inRoot() && JsonToken.END_OBJECT.equals(token)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (JsonToken.VALUE_NULL.equals(token)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (name != null && JsonToken.FIELD_NAME.equals(token) && name.startsWith(INCLUDE)) {
|
||||
p.nextToken();
|
||||
String fileName = p.getText();
|
||||
if (fileName != null) {
|
||||
File includeFile = scanDir != null ? new File(scanDir, fileName) : new File(fileName);
|
||||
if (includeFile.exists()) {
|
||||
recurse(buffer, codec.getFactory().createParser(includeFile), codec, true);
|
||||
|
||||
if (include != null) {
|
||||
String ref = include.textValue();
|
||||
if (ref != null) {
|
||||
File includeFile = scanDir != null ? new File(scanDir, ref) : new File(ref);
|
||||
if (includeFile.exists()) {
|
||||
// load the file into the tree node and continue parsing as normal
|
||||
((ObjectNode) node).remove(INCLUDE);
|
||||
|
||||
TreeNode includeNode;
|
||||
try (JsonParser includeParser = codec.getFactory().createParser(includeFile)) {
|
||||
includeNode = includeParser.readValueAsTree();
|
||||
}
|
||||
|
||||
ObjectReader reader = codec.readerForUpdating(node);
|
||||
TreeNode updated = reader.readValue(includeNode.traverse());
|
||||
JsonParser updatedParser = updated.traverse();
|
||||
updatedParser.nextToken();
|
||||
return super.deserialize(updatedParser, ctx);
|
||||
}
|
||||
} else {
|
||||
buffer.copyCurrentEvent(p);
|
||||
}
|
||||
|
||||
firstToken = false;
|
||||
}
|
||||
|
||||
JsonParser newParser = node.traverse();
|
||||
newParser.nextToken();
|
||||
return super.deserialize(newParser, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,8 +144,8 @@ public class Meta extends OpenApiGeneratorCommand {
|
||||
return support -> {
|
||||
try {
|
||||
File destinationFolder =
|
||||
new File(new File(targetDir.getAbsolutePath()), support.getFolder());
|
||||
File outputFile = new File(destinationFolder, support.getDestinationFilename());
|
||||
new File(new File(targetDir.getAbsolutePath()), support.folder);
|
||||
File outputFile = new File(destinationFolder, support.destinationFilename);
|
||||
|
||||
TemplateManager templateProcessor = new TemplateManager(
|
||||
new TemplateManagerOptions(false, false),
|
||||
@@ -153,13 +153,13 @@ public class Meta extends OpenApiGeneratorCommand {
|
||||
new TemplatePathLocator[]{ new CommonTemplateContentLocator("codegen") }
|
||||
);
|
||||
|
||||
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.getTemplateFile()).getPath());
|
||||
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath());
|
||||
|
||||
String formatted = template;
|
||||
|
||||
Mustache.TemplateLoader loader = name -> templateProcessor.getTemplateReader(name.concat(MUSTACHE_EXTENSION));
|
||||
|
||||
if (support.getTemplateFile().endsWith(MUSTACHE_EXTENSION)) {
|
||||
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
|
||||
LOGGER.info("writing file to {}", outputFile.getAbsolutePath());
|
||||
formatted =
|
||||
Mustache.compiler().withLoader(loader).defaultValue("")
|
||||
|
||||
@@ -28,12 +28,6 @@ public class GenerateBatchTest {
|
||||
private static final String JAXRS_DATELIB_J8_YAML = "jaxrs-datelib-j8.yaml";
|
||||
private static final String JAXRS_DATELIB_J8_YAML_INCLUDE_JSON = "jaxrs-datelib-j8-yaml-include.json";
|
||||
private static final String JAXRS_DATELIB_J8_JSON_INCLUDE_YAML = "jaxrs-datelib-j8-json-include.yaml";
|
||||
private static final String JAXRS_DATELIB_J8_DOUBLE_JSON = "jaxrs-datelib-j8-double.json";
|
||||
private static final String JAXRS_DATELIB_J8_DOUBLE_YAML = "jaxrs-datelib-j8-double.yaml";
|
||||
private static final String JAXRS_DATELIB_J8_NESTED_JSON = "jaxrs-datelib-j8-nested.json";
|
||||
private static final String JAXRS_DATELIB_J8_NESTED_YAML = "jaxrs-datelib-j8-nested.yaml";
|
||||
private static final String JAXRS_DATELIB_J8_NESTED_PROPERTY_MERGE_YAML = "jaxrs-datelib-j8-nested-property-merge.yaml";
|
||||
|
||||
Path workingDirectory;
|
||||
|
||||
@BeforeTest
|
||||
@@ -46,12 +40,7 @@ public class GenerateBatchTest {
|
||||
return new Object[][] {
|
||||
{JAXRS_DATELIB_J8_JSON},
|
||||
{JAXRS_DATELIB_J8_YAML},
|
||||
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML},
|
||||
{JAXRS_DATELIB_J8_DOUBLE_JSON},
|
||||
{JAXRS_DATELIB_J8_DOUBLE_YAML},
|
||||
{JAXRS_DATELIB_J8_NESTED_JSON},
|
||||
{JAXRS_DATELIB_J8_NESTED_YAML},
|
||||
{JAXRS_DATELIB_J8_NESTED_PROPERTY_MERGE_YAML}
|
||||
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"!include": "jaxrs-datelib-j8.json",
|
||||
"!include1": "common/jaxrs-datelib-j8.json"
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
"!include": jaxrs-datelib-j8.yaml
|
||||
"!include": common/jaxrs-datelib-j8.yaml
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
"!include": common/jaxrs-datelib-j8.yaml
|
||||
generatorName: jaxrs-jersey
|
||||
# We expect this property to be ignored because it exists in the importing file
|
||||
outputDir: outputDir-should-be-ignored
|
||||
inputSpec: batch/specs/petstore.yaml
|
||||
# This map should be ignored since it exists in the importing file
|
||||
# We may want to consider merging additionalProperties, but that would depend on user need
|
||||
additionalProperties:
|
||||
hideGenerationTimestamp: true
|
||||
serverPort: 'should-be-ignored'
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"!include": "common/jaxrs-datelib-j8.json",
|
||||
"generatorName": "jaxrs-jersey",
|
||||
"outputDir": "outputDir",
|
||||
"additionalProperties": {
|
||||
"hideGenerationTimestamp": true,
|
||||
"serverPort": "8082"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
"!include": common/jaxrs-datelib-j8.yaml
|
||||
generatorName: jaxrs-jersey
|
||||
outputDir: outputDir
|
||||
additionalProperties:
|
||||
hideGenerationTimestamp: true
|
||||
serverPort: '8082'
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
"!include": jaxrs-datelib-j8-nested-include-property-merge.yaml
|
||||
# We expect this one to "win"
|
||||
outputDir: outputDir
|
||||
additionalProperties:
|
||||
hideGenerationTimestamp: true
|
||||
serverPort: '8082'
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"!include": "jaxrs-datelib-j8-nested-include.json",
|
||||
"inputSpec": "batch/specs/petstore.yaml"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
---
|
||||
"!include": jaxrs-datelib-j8-nested-include.yaml
|
||||
inputSpec: batch/specs/petstore.yaml
|
||||
@@ -1,125 +0,0 @@
|
||||
package org.openapitools.codegen.api;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/**
|
||||
* TemplateDefinition is a type which defines the basics of a template file and target output location.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class TemplateDefinition {
|
||||
private final String templateFile;
|
||||
private final String folder;
|
||||
private final String destinationFilename;
|
||||
|
||||
protected TemplateFileType templateType;
|
||||
|
||||
/**
|
||||
* <p>Constructor for TemplateDefinition.</p>
|
||||
*
|
||||
* @param templateFile a template path relative to user template or embedded template.
|
||||
* @param destinationFilename a target output location for the file, relative to the output directory.
|
||||
*/
|
||||
public TemplateDefinition(String templateFile, String destinationFilename) {
|
||||
this(templateFile, "", destinationFilename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameter-less constructor for TemplateDefinition, used for simplified serialization (see DynamicSettings).
|
||||
*/
|
||||
public TemplateDefinition() {
|
||||
this("", "", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Constructor for TemplateDefinition.</p>
|
||||
*
|
||||
* @param templateFile a template path relative to user template or embedded template.
|
||||
* @param folder a folder in the target output directory in which to place the target file.
|
||||
* @param destinationFilename a target output location for the file, relative to the output directory.
|
||||
*/
|
||||
public TemplateDefinition(String templateFile, String folder, String destinationFilename) {
|
||||
if (templateFile == null) throw new IllegalArgumentException("templateFile may not be null.");
|
||||
if (folder == null) throw new IllegalArgumentException("folder may not be null.");
|
||||
if (destinationFilename == null) throw new IllegalArgumentException("destinationFilename may not be null.");
|
||||
|
||||
this.templateFile = templateFile;
|
||||
this.folder = folder;
|
||||
this.destinationFilename = destinationFilename;
|
||||
this.templateType = TemplateFileType.SupportingFiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets target output location for the file, relative to the output directory.
|
||||
*
|
||||
* @return a target output location for the file, relative to the output directory.
|
||||
*/
|
||||
public String getDestinationFilename() {
|
||||
return destinationFilename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a folder in the target output directory in which to place the target file.
|
||||
*
|
||||
* @return a a folder in the target output directory in which to place the target file.
|
||||
*/
|
||||
public String getFolder() {
|
||||
return folder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a template path relative to user template or embedded template.
|
||||
*
|
||||
* @return a template path relative to user template or embedded template.
|
||||
*/
|
||||
public String getTemplateFile() {
|
||||
return templateFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the type of template
|
||||
*
|
||||
* @return a {@link TemplateFileType} enum which defines the type of this template.
|
||||
*/
|
||||
public TemplateFileType getTemplateType() {
|
||||
return templateType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the type of template
|
||||
*
|
||||
* @param templateType a {@link TemplateFileType} enum which defines the type of this template
|
||||
*/
|
||||
public void setTemplateType(TemplateFileType templateType) {
|
||||
this.templateType = templateType;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof TemplateDefinition)) return false;
|
||||
TemplateDefinition that = (TemplateDefinition) o;
|
||||
return getTemplateFile().equals(that.getTemplateFile()) &&
|
||||
getFolder().equals(that.getFolder()) &&
|
||||
getDestinationFilename().equals(that.getDestinationFilename()) &&
|
||||
getTemplateType() == that.getTemplateType();
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType());
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]")
|
||||
.add("templateFile='" + templateFile + "'")
|
||||
.add("folder='" + folder + "'")
|
||||
.add("destinationFilename='" + destinationFilename + "'")
|
||||
.add("templateType=" + templateType)
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package org.openapitools.codegen.api;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/**
|
||||
* Represents the type of a generator's templating files. These types of template files may be processed differently
|
||||
* (multiple times per definition, or conditionally based on user or generator configuration).
|
||||
*/
|
||||
public enum TemplateFileType {
|
||||
API(Constants.APIS),
|
||||
Model(Constants.MODELS),
|
||||
APIDocs(Constants.API_DOCS),
|
||||
ModelDocs(Constants.MODEL_DOCS),
|
||||
APITests(Constants.API_TESTS),
|
||||
ModelTests(Constants.MODEL_TESTS),
|
||||
SupportingFiles(Constants.SUPPORTING_FILES);
|
||||
|
||||
private final String templateType;
|
||||
|
||||
TemplateFileType(String templateType) { this.templateType = templateType; }
|
||||
|
||||
/**
|
||||
* Returns the value for this template file type
|
||||
*
|
||||
* @return The template type of this enum.
|
||||
*/
|
||||
public String value() { return this.templateType; }
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", TemplateFileType.class.getSimpleName() + "[", "]")
|
||||
.add("templateType='" + templateType + "'")
|
||||
.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the {@link TemplateFileType} for an input string.
|
||||
*
|
||||
* @param templateType a {@link java.lang.String} object.
|
||||
* @return a {@link TemplateFileType} object.
|
||||
*/
|
||||
public static TemplateFileType forTemplateType(String templateType) {
|
||||
for (TemplateFileType value : values()) {
|
||||
if (value.templateType.equals(templateType)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("templateType not found in the available values.");
|
||||
}
|
||||
|
||||
public static class Constants {
|
||||
public static final String APIS = "apis";
|
||||
public static final String MODELS = "models";
|
||||
public static final String SUPPORTING_FILES = "supportingFiles";
|
||||
public static final String MODEL_TESTS = "modelTests";
|
||||
public static final String MODEL_DOCS = "modelDocs";
|
||||
public static final String API_TESTS = "apiTests";
|
||||
public static final String API_DOCS = "apiDocs";
|
||||
}
|
||||
}
|
||||
@@ -45,16 +45,6 @@ public interface TemplatingEngineAdapter {
|
||||
*/
|
||||
String[] getFileExtensions();
|
||||
|
||||
/**
|
||||
* Determine if the adapter handles compilation of the file
|
||||
* @param filename The template filename
|
||||
*
|
||||
* @return True if the file should be compiled by this adapter, else false.
|
||||
*/
|
||||
default boolean handlesFile(String filename) {
|
||||
return filename != null && filename.length() > 0 && Arrays.stream(getFileExtensions()).anyMatch(i -> filename.endsWith("." + i));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a template into a string
|
||||
*
|
||||
@@ -75,10 +65,9 @@ public interface TemplatingEngineAdapter {
|
||||
* @param templateFile The original target filename
|
||||
* @return True if the template is available in the template search path, false if it can not be found
|
||||
*/
|
||||
@SuppressWarnings({"java:S2093"}) // ignore java:S2093 because we have double-assignment to the closeable
|
||||
default boolean templateExists(TemplatingExecutor generator, String templateFile) {
|
||||
return Arrays.stream(getFileExtensions()).anyMatch(ext -> {
|
||||
int idx = templateFile.lastIndexOf('.');
|
||||
int idx = templateFile.lastIndexOf(".");
|
||||
String baseName;
|
||||
if (idx > 0 && idx < templateFile.length() - 1) {
|
||||
baseName = templateFile.substring(0, idx);
|
||||
|
||||
@@ -442,7 +442,7 @@ public class WorkflowSettings {
|
||||
// check to see if the folder exists
|
||||
if (f.exists() && f.isDirectory()) {
|
||||
uri = f.toURI();
|
||||
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
|
||||
this.templateDir = Paths.get(uri).toAbsolutePath().toString();
|
||||
} else {
|
||||
URL url = this.getClass().getClassLoader().getResource(templateDir);
|
||||
if (url != null) {
|
||||
|
||||
Binary file not shown.
@@ -1,5 +1,6 @@
|
||||
#Thu Jan 30 22:14:34 EST 2020
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
22
modules/openapi-generator-gradle-plugin/gradlew
vendored
22
modules/openapi-generator-gradle-plugin/gradlew
vendored
@@ -1,21 +1,5 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
@@ -44,7 +28,7 @@ APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
DEFAULT_JVM_OPTS=""
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
@@ -125,8 +109,8 @@ if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
184
modules/openapi-generator-gradle-plugin/gradlew.bat
vendored
184
modules/openapi-generator-gradle-plugin/gradlew.bat
vendored
@@ -1,100 +1,84 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
|
||||
@@ -94,7 +94,6 @@
|
||||
<tasks>
|
||||
<!-- calls "clean assemble install" -->
|
||||
<task>clean</task>
|
||||
<task>check</task>
|
||||
<task>assemble</task>
|
||||
<task>publishToMavenLocal</task>
|
||||
<task>publishPluginMavenPublicationToMavenLocal</task>
|
||||
|
||||
@@ -5,7 +5,6 @@ import org.gradle.testkit.runner.TaskOutcome
|
||||
import org.testng.annotations.Test
|
||||
import java.io.File
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class GenerateTaskDslTest : TestBase() {
|
||||
@@ -79,17 +78,17 @@ class GenerateTaskDslTest : TestBase() {
|
||||
// Act
|
||||
val resultFirstRun = GradleRunner.create()
|
||||
.withProjectDir(temp)
|
||||
.withArguments("openApiGenerate", "--info")
|
||||
.withArguments("openApiGenerate")
|
||||
.withPluginClasspath()
|
||||
.build()
|
||||
val resultSecondRun = GradleRunner.create()
|
||||
.withProjectDir(temp)
|
||||
.withArguments("openApiGenerate", "--info")
|
||||
.withArguments("openApiGenerate")
|
||||
.withPluginClasspath()
|
||||
.build()
|
||||
|
||||
// Assert
|
||||
assertFalse(resultFirstRun.output.contains("Task :openApiGenerate UP-TO-DATE"), "First run should not be up-to-date")
|
||||
assertTrue(resultFirstRun.output.contains("Task ':openApiGenerate' is not up-to-date"), "First run should not be up-to-date")
|
||||
assertTrue(resultSecondRun.output.contains("Task :openApiGenerate UP-TO-DATE"), "Task of second run should be up-to-date")
|
||||
}
|
||||
|
||||
@@ -104,7 +103,7 @@ class GenerateTaskDslTest : TestBase() {
|
||||
// Act
|
||||
val resultFirstRun = GradleRunner.create()
|
||||
.withProjectDir(temp)
|
||||
.withArguments("openApiGenerate", "--build-cache", "--info")
|
||||
.withArguments("openApiGenerate", "--build-cache")
|
||||
.withPluginClasspath()
|
||||
.build()
|
||||
|
||||
@@ -114,22 +113,13 @@ class GenerateTaskDslTest : TestBase() {
|
||||
// re-run
|
||||
val resultSecondRun = GradleRunner.create()
|
||||
.withProjectDir(temp)
|
||||
.withArguments("openApiGenerate", "--build-cache", "--info")
|
||||
.withArguments("openApiGenerate", "--build-cache")
|
||||
.withPluginClasspath()
|
||||
.build()
|
||||
|
||||
// re-run without deletes
|
||||
val resultThirdRun = GradleRunner.create()
|
||||
.withProjectDir(temp)
|
||||
.withArguments("openApiGenerate", "--build-cache", "--info")
|
||||
.withPluginClasspath()
|
||||
.build()
|
||||
|
||||
// Assert
|
||||
assertTrue(resultFirstRun.output.contains("No history is available."), "First run should not be up-to-date")
|
||||
assertFalse(resultSecondRun.output.contains("No history is available."), "Task of second run should be from cache")
|
||||
assertTrue(resultSecondRun.output.contains("has been removed."), "Task of second run should detect cache changes for untracked files")
|
||||
assertTrue(resultThirdRun.output.contains("Skipping task ':openApiGenerate' as it is up-to-date."), "Task of third run should not require rebuild")
|
||||
assertTrue(resultFirstRun.output.contains("Task ':openApiGenerate' is not up-to-date"), "First run should not be up-to-date")
|
||||
assertTrue(resultSecondRun.output.contains("Task :openApiGenerate FROM-CACHE"), "Task of second run should be from cache")
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -32,7 +32,7 @@ class ValidateTaskDslTest : TestBase() {
|
||||
.buildAndFail()
|
||||
|
||||
// Assert
|
||||
assertTrue(result.output.contains("some_location' specified for property 'inputSpec' does not exist"), "Unexpected/no message presented to the user for a spec pointing to an invalid URI.")
|
||||
assertTrue(result.output.contains("unable to read location `some_location`"), "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}")
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<groupId>org.openapitools</groupId>
|
||||
<artifactId>openapi-generator-maven-plugin</artifactId>
|
||||
<!-- RELEASE_VERSION -->
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
<version>4.3.1</version>
|
||||
<!-- /RELEASE_VERSION -->
|
||||
<executions>
|
||||
<execution>
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
<description>maven plugin to build modules from OpenAPI Generator</description>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<sonar.exclusions>**/src/main/java/org/openapitools/codegen/plugin/**/*</sonar.exclusions>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
<springfox-version>3.0.0</springfox-version>
|
||||
<junit-version>4.13</junit-version>
|
||||
<jackson-version>2.10.2</jackson-version>
|
||||
<sonar.exclusions>**/org/openapitools/codegen/online/**/*</sonar.exclusions>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
||||
@@ -20,7 +20,6 @@ package org.openapitools.codegen;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.parser.core.models.AuthorizationValue;
|
||||
|
||||
import org.openapitools.codegen.api.TemplateDefinition;
|
||||
import org.openapitools.codegen.auth.AuthParser;
|
||||
|
||||
import java.util.List;
|
||||
@@ -29,7 +28,6 @@ public class ClientOptInput {
|
||||
private CodegenConfig config;
|
||||
private OpenAPI openAPI;
|
||||
private List<AuthorizationValue> auths;
|
||||
private List<TemplateDefinition> userDefinedTemplates;
|
||||
|
||||
public ClientOptInput openAPI(OpenAPI openAPI) {
|
||||
this.setOpenAPI(openAPI);
|
||||
@@ -41,11 +39,6 @@ public class ClientOptInput {
|
||||
return this;
|
||||
}
|
||||
|
||||
public ClientOptInput userDefinedTemplates(List<TemplateDefinition> userDefinedTemplates) {
|
||||
this.userDefinedTemplates = userDefinedTemplates;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public ClientOptInput auth(String urlEncodedAuthString) {
|
||||
this.setAuth(urlEncodedAuthString);
|
||||
@@ -72,14 +65,7 @@ public class ClientOptInput {
|
||||
return config;
|
||||
}
|
||||
|
||||
public List<TemplateDefinition> getUserDefinedTemplates() {
|
||||
// not deprecated as this is added to match other functionality, we need to move to Context<?> instead of ClientOptInput.
|
||||
return userDefinedTemplates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the generator/config instance
|
||||
*
|
||||
* @deprecated use {@link #config(CodegenConfig)} instead
|
||||
* @param config codegen config
|
||||
*/
|
||||
@@ -98,8 +84,6 @@ public class ClientOptInput {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the OpenAPI document
|
||||
*
|
||||
* @deprecated use {@link #openAPI(OpenAPI)} instead
|
||||
* @param openAPI the specification
|
||||
*/
|
||||
|
||||
@@ -292,6 +292,4 @@ public interface CodegenConfig {
|
||||
boolean isRemoveEnumValuePrefix();
|
||||
|
||||
void setRemoveEnumValuePrefix(boolean removeEnumValuePrefix);
|
||||
|
||||
Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ public class CodegenConstants {
|
||||
public static final String MODEL_DOCS = "modelDocs";
|
||||
public static final String API_TESTS = "apiTests";
|
||||
public static final String API_DOCS = "apiDocs";
|
||||
|
||||
public static final String WITH_XML = "withXml";
|
||||
public static final String SKIP_FORM_MODEL = "skipFormModel";
|
||||
/* /end System Properties */
|
||||
|
||||
@@ -550,13 +550,6 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
||||
this.multipleOf = multipleOf;
|
||||
}
|
||||
|
||||
// indicates if the model component has validation on the root level schema
|
||||
// this will be true when minItems or minProperties is set
|
||||
public boolean hasValidation() {
|
||||
boolean val = (maxItems != null || minItems != null || minProperties != null || maxProperties != null || minLength != null || maxLength != null || multipleOf != null || pattern != null || minimum != null || maximum != null || Boolean.TRUE.equals(uniqueItems) || Boolean.TRUE.equals(exclusiveMaximum) || Boolean.TRUE.equals(exclusiveMinimum));
|
||||
return val;
|
||||
}
|
||||
|
||||
public List<CodegenProperty> getReadOnlyVars() {
|
||||
return readOnlyVars;
|
||||
}
|
||||
|
||||
@@ -247,9 +247,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
// make openapi available to all methods
|
||||
protected OpenAPI openAPI;
|
||||
|
||||
// A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`.
|
||||
private Map<String, Schema> modelNameToSchemaCache;
|
||||
|
||||
public List<CliOption> cliOptions() {
|
||||
return cliOptions;
|
||||
}
|
||||
@@ -453,23 +450,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
return objs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a map from model name to Schema for efficient lookup.
|
||||
*
|
||||
* @return map from model name to Schema.
|
||||
*/
|
||||
protected Map<String, Schema> getModelNameToSchemaCache() {
|
||||
if (modelNameToSchemaCache == null) {
|
||||
// Create a cache to efficiently lookup schema based on model name.
|
||||
Map<String, Schema> m = new HashMap<String, Schema>();
|
||||
ModelUtils.getSchemas(openAPI).forEach((key, schema) -> {
|
||||
m.put(toModelName(key), schema);
|
||||
});
|
||||
modelNameToSchemaCache = Collections.unmodifiableMap(m);
|
||||
}
|
||||
return modelNameToSchemaCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index all CodegenModels by model name.
|
||||
*
|
||||
@@ -1313,13 +1293,14 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
* @param name the variable name
|
||||
* @return the sanitized variable name
|
||||
*/
|
||||
public String toVarName(final String name) {
|
||||
public String toVarName(String name) {
|
||||
if (reservedWords.contains(name)) {
|
||||
return escapeReservedWord(name);
|
||||
} else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains("" + ((char) character)))) {
|
||||
return escape(name, specialCharReplacements, null, null);
|
||||
} else {
|
||||
return name;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1337,7 +1318,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
return escape(name, specialCharReplacements, null, null);
|
||||
}
|
||||
return name;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1991,7 +1971,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
return "oneOf<" + String.join(",", names) + ">";
|
||||
}
|
||||
|
||||
public Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings) {
|
||||
protected Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings) {
|
||||
return ModelUtils.unaliasSchema(this.openAPI, schema, usedImportMappings);
|
||||
}
|
||||
|
||||
@@ -2215,8 +2195,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the OpenAPI schema name to a model name suitable for the current code generator.
|
||||
* May be overriden for each programming language.
|
||||
* Output the proper model name (capitalized).
|
||||
* In case the name belongs to the TypeSystem it won't be renamed.
|
||||
*
|
||||
* @param name the name of the model
|
||||
@@ -2226,33 +2205,8 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
return camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix);
|
||||
}
|
||||
|
||||
private static class NamedSchema {
|
||||
private NamedSchema(String name, Schema s) {
|
||||
this.name = name;
|
||||
this.schema = s;
|
||||
}
|
||||
private String name;
|
||||
private Schema schema;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
NamedSchema that = (NamedSchema) o;
|
||||
return Objects.equals(name, that.name) &&
|
||||
Objects.equals(schema, that.schema);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(name, schema);
|
||||
}
|
||||
}
|
||||
|
||||
Map<NamedSchema, CodegenProperty> schemaCodegenPropertyCache = new HashMap<NamedSchema, CodegenProperty>();
|
||||
|
||||
/**
|
||||
* Convert OAS Model object to Codegen Model object.
|
||||
* Convert OAS Model object to Codegen Model object
|
||||
*
|
||||
* @param name the name of the model
|
||||
* @param schema OAS Model object
|
||||
@@ -2318,7 +2272,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
m.isArrayModel = true;
|
||||
m.arrayModelType = fromProperty(name, schema).complexType;
|
||||
addParentContainer(m, name, schema);
|
||||
ModelUtils.syncValidationProperties(schema, m);
|
||||
} else if (schema instanceof ComposedSchema) {
|
||||
final ComposedSchema composed = (ComposedSchema) schema;
|
||||
Map<String, Schema> properties = new LinkedHashMap<String, Schema>();
|
||||
@@ -2537,9 +2490,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
} else { // type is number and without format
|
||||
m.isNumber = Boolean.TRUE;
|
||||
}
|
||||
} else if (ModelUtils.isFreeFormObject(openAPI, schema)) {
|
||||
addAdditionPropertiesToCodeGenModel(m, schema);
|
||||
ModelUtils.syncValidationProperties(schema, m);
|
||||
}
|
||||
|
||||
if (Boolean.TRUE.equals(schema.getNullable())) {
|
||||
@@ -2611,6 +2561,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
postProcessModelProperty(m, prop);
|
||||
}
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
@@ -2862,7 +2813,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
String currentSchemaName = thisSchemaName;
|
||||
while (true) {
|
||||
for (String childName : schemas.keySet()) {
|
||||
if (childName.equals(thisSchemaName)) {
|
||||
if (childName == thisSchemaName) {
|
||||
continue;
|
||||
}
|
||||
Schema child = schemas.get(childName);
|
||||
@@ -2875,8 +2826,9 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
if (ref == null) {
|
||||
// for schemas with no ref, it is not possible to build the discriminator map
|
||||
// because ref is how we get the model name
|
||||
// we hit this use case when an allOf composed schema contains an inline schema
|
||||
continue;
|
||||
// we only hit this use case for a schema with inline composed schemas, and one of those
|
||||
// schemas also has inline composed schemas
|
||||
throw new RuntimeException("Invalid inline schema defined in allOf in '" + childName + "'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the allOf schemas must use $ref. Change this inline definition to a $ref definition");
|
||||
}
|
||||
String parentName = ModelUtils.getSimpleRef(ref);
|
||||
if (parentName.equals(currentSchemaName)) {
|
||||
@@ -3029,13 +2981,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert OAS Property object to Codegen Property object.
|
||||
*
|
||||
* The return value is cached. An internal cache is looked up to determine
|
||||
* if the CodegenProperty return value has already been instantiated for
|
||||
* the (String name, Schema p) arguments.
|
||||
* Any subsequent processing of the CodegenModel return value must be idempotent
|
||||
* for a given (String name, Schema schema).
|
||||
* Convert OAS Property object to Codegen Property object
|
||||
*
|
||||
* @param name name of the property
|
||||
* @param p OAS property schema
|
||||
@@ -3047,12 +2993,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
return null;
|
||||
}
|
||||
LOGGER.debug("debugging fromProperty for " + name + " : " + p);
|
||||
NamedSchema ns = new NamedSchema(name, p);
|
||||
CodegenProperty cpc = schemaCodegenPropertyCache.get(ns);
|
||||
if (cpc != null) {
|
||||
LOGGER.debug("Cached fromProperty for " + name + " : " + p.getName());
|
||||
return cpc;
|
||||
}
|
||||
|
||||
// unalias schema
|
||||
p = unaliasSchema(p, importMapping);
|
||||
|
||||
@@ -3352,7 +3293,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
}
|
||||
|
||||
LOGGER.debug("debugging from property return: " + property);
|
||||
schemaCodegenPropertyCache.put(ns, property);
|
||||
return property;
|
||||
}
|
||||
|
||||
@@ -4819,6 +4759,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
|
||||
final String key = entry.getKey();
|
||||
final Schema prop = entry.getValue();
|
||||
|
||||
if (prop == null) {
|
||||
LOGGER.warn("Please report the issue. There shouldn't be null property for " + key);
|
||||
} else {
|
||||
@@ -5032,15 +4973,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
return library;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if current active library equals to passed
|
||||
* @param library - library to be compared with
|
||||
* @return {@code true} if passed library is active, {@code false} otherwise
|
||||
*/
|
||||
public final boolean isLibrary(String library) {
|
||||
return library.equals(this.library);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Git host.
|
||||
*
|
||||
@@ -6438,9 +6370,6 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
.featureSet(builder.build()).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* An map entry for cached sanitized names.
|
||||
*/
|
||||
private static class SanitizeNameOptions {
|
||||
public SanitizeNameOptions(String name, String removeCharRegEx, List<String> exceptions) {
|
||||
this.name = name;
|
||||
@@ -6448,7 +6377,7 @@ public class DefaultCodegen implements CodegenConfig {
|
||||
if (exceptions != null) {
|
||||
this.exceptions = Collections.unmodifiableList(exceptions);
|
||||
} else {
|
||||
this.exceptions = Collections.emptyList();
|
||||
this.exceptions = Collections.unmodifiableList(new ArrayList<>());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
|
||||
package org.openapitools.codegen;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import io.swagger.v3.core.util.Json;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.Operation;
|
||||
@@ -30,16 +29,13 @@ import io.swagger.v3.oas.models.media.Schema;
|
||||
import io.swagger.v3.oas.models.parameters.Parameter;
|
||||
import io.swagger.v3.oas.models.security.*;
|
||||
import io.swagger.v3.oas.models.tags.Tag;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.io.comparator.PathFileComparator;
|
||||
import org.apache.commons.lang3.ObjectUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openapitools.codegen.api.TemplateDefinition;
|
||||
import org.openapitools.codegen.api.TemplatePathLocator;
|
||||
import org.openapitools.codegen.api.TemplateProcessor;
|
||||
import org.openapitools.codegen.config.GlobalSettings;
|
||||
import org.openapitools.codegen.api.TemplatingEngineAdapter;
|
||||
import org.openapitools.codegen.api.TemplateFileType;
|
||||
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
|
||||
import org.openapitools.codegen.languages.PythonClientExperimentalCodegen;
|
||||
import org.openapitools.codegen.meta.GeneratorMetadata;
|
||||
@@ -62,7 +58,6 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.removeStart;
|
||||
@@ -91,8 +86,6 @@ public class DefaultGenerator implements Generator {
|
||||
private Map<String, String> generatorPropertyDefaults = new HashMap<>();
|
||||
protected TemplateProcessor templateProcessor = null;
|
||||
|
||||
private List<TemplateDefinition> userDefinedTemplates = new ArrayList<>();
|
||||
|
||||
|
||||
public DefaultGenerator() {
|
||||
this(false);
|
||||
@@ -109,10 +102,6 @@ public class DefaultGenerator implements Generator {
|
||||
this.opts = opts;
|
||||
this.openAPI = opts.getOpenAPI();
|
||||
this.config = opts.getConfig();
|
||||
List<TemplateDefinition> userFiles = opts.getUserDefinedTemplates();
|
||||
if (userFiles != null) {
|
||||
this.userDefinedTemplates = ImmutableList.copyOf(userFiles);
|
||||
}
|
||||
|
||||
TemplateManagerOptions templateManagerOptions = new TemplateManagerOptions(this.config.isEnableMinimalUpdate(),this.config.isSkipOverwrite());
|
||||
|
||||
@@ -459,19 +448,8 @@ public class DefaultGenerator implements Generator {
|
||||
Schema schema = schemas.get(name);
|
||||
|
||||
if (ModelUtils.isFreeFormObject(this.openAPI, schema)) { // check to see if it'a a free-form object
|
||||
// there are 3 free form use cases
|
||||
// 1. free form with no validation that is not allOf included in any composed schemas
|
||||
// 2. free form with validation
|
||||
// 3. free form that is allOf included in any composed schemas
|
||||
// this use case arises when using interface schemas
|
||||
// generators may choose to make models for use case 2 + 3
|
||||
Schema refSchema = new Schema();
|
||||
refSchema.set$ref("#/components/schemas/"+name);
|
||||
Schema unaliasedSchema = config.unaliasSchema(refSchema, config.importMapping());
|
||||
if (unaliasedSchema.get$ref() == null) {
|
||||
LOGGER.info("Model {} not generated since it's a free-form object", name);
|
||||
continue;
|
||||
}
|
||||
LOGGER.info("Model {} not generated since it's a free-form object", name);
|
||||
continue;
|
||||
} else if (ModelUtils.isMapSchema(schema)) { // check to see if it's a "map" model
|
||||
// A composed schema (allOf, oneOf, anyOf) is considered a Map schema if the additionalproperties attribute is set
|
||||
// for that composed schema. However, in the case of a composed schema, the properties are defined or referenced
|
||||
@@ -701,8 +679,8 @@ public class DefaultGenerator implements Generator {
|
||||
for (SupportingFile support : config.supportingFiles()) {
|
||||
try {
|
||||
String outputFolder = config.outputFolder();
|
||||
if (StringUtils.isNotEmpty(support.getFolder())) {
|
||||
outputFolder += File.separator + support.getFolder();
|
||||
if (StringUtils.isNotEmpty(support.folder)) {
|
||||
outputFolder += File.separator + support.folder;
|
||||
}
|
||||
File of = new File(outputFolder);
|
||||
if (!of.isDirectory()) {
|
||||
@@ -710,20 +688,20 @@ public class DefaultGenerator implements Generator {
|
||||
once(LOGGER).debug("Output directory {} not created. It {}.", outputFolder, of.exists() ? "already exists." : "may not have appropriate permissions.");
|
||||
}
|
||||
}
|
||||
String outputFilename = new File(support.getDestinationFilename()).isAbsolute() // split
|
||||
? support.getDestinationFilename()
|
||||
: outputFolder + File.separator + support.getDestinationFilename().replace('/', File.separatorChar);
|
||||
String outputFilename = new File(support.destinationFilename).isAbsolute() // split
|
||||
? support.destinationFilename
|
||||
: outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar);
|
||||
|
||||
boolean shouldGenerate = true;
|
||||
if (supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) {
|
||||
shouldGenerate = supportingFilesToGenerate.contains(support.getDestinationFilename());
|
||||
shouldGenerate = supportingFilesToGenerate.contains(support.destinationFilename);
|
||||
}
|
||||
|
||||
File written = processTemplateToFile(bundle, support.getTemplateFile(), outputFilename, shouldGenerate, CodegenConstants.SUPPORTING_FILES);
|
||||
File written = processTemplateToFile(bundle, support.templateFile, outputFilename, shouldGenerate, CodegenConstants.SUPPORTING_FILES);
|
||||
if (written != null) {
|
||||
files.add(written);
|
||||
if (config.isEnablePostProcessFile() && !dryRun) {
|
||||
config.postProcessFile(written, "supporting-file");
|
||||
config.postProcessFile(written, "api-doc");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -775,9 +753,6 @@ public class DefaultGenerator implements Generator {
|
||||
bundle.put("basePathWithoutHost", basePathWithoutHost);
|
||||
bundle.put("scheme", URLPathUtils.getScheme(url, config));
|
||||
bundle.put("host", url.getHost());
|
||||
if (url.getPort() != 80 ) {
|
||||
bundle.put("port", url.getPort());
|
||||
}
|
||||
bundle.put("contextPath", contextPath);
|
||||
bundle.put("apiInfo", apis);
|
||||
bundle.put("models", allModels);
|
||||
@@ -870,8 +845,6 @@ public class DefaultGenerator implements Generator {
|
||||
|
||||
config.processOpenAPI(openAPI);
|
||||
|
||||
processUserDefinedTemplates();
|
||||
|
||||
List<File> files = new ArrayList<>();
|
||||
// models
|
||||
List<String> filteredSchemas = ModelUtils.getSchemasUsedOnlyInFormParam(openAPI);
|
||||
@@ -935,86 +908,11 @@ public class DefaultGenerator implements Generator {
|
||||
return files;
|
||||
}
|
||||
|
||||
private void processUserDefinedTemplates() {
|
||||
// TODO: initial behavior is "merge" user defined with built-in templates. consider offering user a "replace" option.
|
||||
if (userDefinedTemplates != null && !userDefinedTemplates.isEmpty()) {
|
||||
Map<String, SupportingFile> supportingFilesMap = config.supportingFiles().stream()
|
||||
.collect(Collectors.toMap(TemplateDefinition::getTemplateFile, Function.identity()));
|
||||
|
||||
// TemplateFileType.SupportingFiles
|
||||
userDefinedTemplates.stream()
|
||||
.filter(i -> i.getTemplateType().equals(TemplateFileType.SupportingFiles))
|
||||
.forEach(userDefinedTemplate -> {
|
||||
SupportingFile newFile = new SupportingFile(
|
||||
userDefinedTemplate.getTemplateFile(),
|
||||
userDefinedTemplate.getFolder(),
|
||||
userDefinedTemplate.getDestinationFilename()
|
||||
);
|
||||
if (supportingFilesMap.containsKey(userDefinedTemplate.getTemplateFile())) {
|
||||
SupportingFile f = supportingFilesMap.get(userDefinedTemplate.getTemplateFile());
|
||||
config.supportingFiles().remove(f);
|
||||
|
||||
if (!f.isCanOverwrite()) {
|
||||
newFile.doNotOverwrite();
|
||||
}
|
||||
}
|
||||
config.supportingFiles().add(newFile);
|
||||
});
|
||||
|
||||
// Others, excluding TemplateFileType.SupportingFiles
|
||||
userDefinedTemplates.stream()
|
||||
.filter(i -> !i.getTemplateType().equals(TemplateFileType.SupportingFiles))
|
||||
.forEach(userDefinedTemplate -> {
|
||||
// determine file extension…
|
||||
// if template is in format api.ts.mustache, we'll extract .ts
|
||||
// if user has provided an example destination filename, we'll use that extension
|
||||
String templateFile = userDefinedTemplate.getTemplateFile();
|
||||
int lastSeparator = templateFile.lastIndexOf('.');
|
||||
String templateExt = FilenameUtils.getExtension(templateFile.substring(0, lastSeparator));
|
||||
if (StringUtils.isBlank(templateExt)) {
|
||||
// hack: destination filename in this scenario might be a suffix like Impl.java
|
||||
templateExt = userDefinedTemplate.getDestinationFilename();
|
||||
} else {
|
||||
templateExt = StringUtils.prependIfMissing(templateExt, ".");
|
||||
}
|
||||
|
||||
switch (userDefinedTemplate.getTemplateType()) {
|
||||
case API:
|
||||
config.apiTemplateFiles().put(templateFile, templateExt);
|
||||
break;
|
||||
case Model:
|
||||
config.modelTemplateFiles().put(templateFile, templateExt);
|
||||
break;
|
||||
case APIDocs:
|
||||
config.apiDocTemplateFiles().put(templateFile, templateExt);
|
||||
break;
|
||||
case ModelDocs:
|
||||
config.modelDocTemplateFiles().put(templateFile, templateExt);
|
||||
break;
|
||||
case APITests:
|
||||
config.apiTestTemplateFiles().put(templateFile, templateExt);
|
||||
break;
|
||||
case ModelTests:
|
||||
config.modelTestTemplateFiles().put(templateFile, templateExt);
|
||||
break;
|
||||
case SupportingFiles:
|
||||
// excluded by filter
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename, boolean shouldGenerate, String skippedByOption) throws IOException {
|
||||
String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar);
|
||||
File target = new File(adjustedOutputFilename);
|
||||
if (ignoreProcessor.allowsFile(target)) {
|
||||
if (shouldGenerate) {
|
||||
Path outDir = java.nio.file.Paths.get(this.config.getOutputDir()).toAbsolutePath();
|
||||
Path absoluteTarget = target.toPath().toAbsolutePath();
|
||||
if (!absoluteTarget.startsWith(outDir)) {
|
||||
throw new RuntimeException(String.format(Locale.ROOT, "Target files must be generated within the output directory; absoluteTarget=%s outDir=%s", absoluteTarget, outDir));
|
||||
}
|
||||
return this.templateProcessor.write(templateData,templateName, target);
|
||||
} else {
|
||||
this.templateProcessor.skip(target.toPath(), String.format(Locale.ROOT, "Skipped by %s options supplied by user.", skippedByOption));
|
||||
|
||||
@@ -17,28 +17,53 @@
|
||||
|
||||
package org.openapitools.codegen;
|
||||
|
||||
import org.openapitools.codegen.api.TemplateDefinition;
|
||||
import org.openapitools.codegen.api.TemplateFileType;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/**
|
||||
* Defines the template definition for a "supporting file", that is any file which is generic and not bound to
|
||||
* api/model definitions and their relevant docs or tests.
|
||||
*
|
||||
* Supporting files are generated once for an entire application while api/model bound definitions are generated multiple
|
||||
* times according to their target use.
|
||||
*/
|
||||
public class SupportingFile extends TemplateDefinition {
|
||||
private boolean canOverwrite = true;
|
||||
public class SupportingFile {
|
||||
public String templateFile;
|
||||
public String folder;
|
||||
public String destinationFilename;
|
||||
public boolean canOverwrite = true;
|
||||
|
||||
public SupportingFile(String templateFile, String destinationFilename) {
|
||||
this(templateFile, "", destinationFilename);
|
||||
}
|
||||
|
||||
public SupportingFile(String templateFile, String folder, String destinationFilename) {
|
||||
super(templateFile, folder, destinationFilename);
|
||||
this.templateFile = templateFile;
|
||||
this.folder = folder;
|
||||
this.destinationFilename = destinationFilename;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(templateFile, folder, destinationFilename, canOverwrite);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
SupportingFile that = (SupportingFile) o;
|
||||
|
||||
return Objects.equals(templateFile, that.templateFile) &&
|
||||
Objects.equals(folder, that.folder) &&
|
||||
Objects.equals(destinationFilename, that.destinationFilename) &&
|
||||
canOverwrite == that.canOverwrite;
|
||||
}
|
||||
|
||||
@SuppressWarnings("StringBufferReplaceableByString")
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("SupportingFile:").append("\n");
|
||||
builder.append("\ttemplateFile: ").append(templateFile).append("\n");
|
||||
builder.append("\tfolder: ").append(folder).append("\n");
|
||||
builder.append("\tcanOverwrite: ").append(Boolean.valueOf(canOverwrite)).append("\n");
|
||||
builder.append("\tdestinationFilename: ").append(destinationFilename).append("\n");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,54 +75,6 @@ public class SupportingFile extends TemplateDefinition {
|
||||
canOverwrite = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the type of template
|
||||
*
|
||||
* @param templateType a {@link TemplateFileType} enum which defines the type of this template
|
||||
*/
|
||||
@Override
|
||||
public void setTemplateType(TemplateFileType templateType) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the type of template
|
||||
*
|
||||
* @return a {@link TemplateFileType} enum which defines the type of this template.
|
||||
*/
|
||||
@Override
|
||||
public TemplateFileType getTemplateType() {
|
||||
return TemplateFileType.SupportingFiles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof SupportingFile)) return false;
|
||||
if (!super.equals(o)) return false;
|
||||
SupportingFile that = (SupportingFile) o;
|
||||
return isCanOverwrite() == that.isCanOverwrite();
|
||||
}
|
||||
|
||||
public boolean isCanOverwrite() {
|
||||
return canOverwrite;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(super.hashCode(), isCanOverwrite());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", SupportingFile.class.getSimpleName() + "[", "]")
|
||||
.add("templateFile='" + getTemplateFile() + "'")
|
||||
.add("folder='" + getFolder() + "'")
|
||||
.add("destinationFilename='" + getDestinationFilename() + "'")
|
||||
.add("canOverwrite=" + isCanOverwrite())
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.openapitools.codegen;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openapitools.codegen.api.TemplatePathLocator;
|
||||
import org.openapitools.codegen.api.TemplateProcessor;
|
||||
@@ -13,8 +12,14 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -54,10 +59,6 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
||||
throw new TemplateNotFoundException(name);
|
||||
}
|
||||
|
||||
if (name == null || name.contains("..")) {
|
||||
throw new IllegalArgumentException("Template location must be constrained to template directory.");
|
||||
}
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
@@ -103,12 +104,7 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
||||
* @param name The location of the template
|
||||
* @return The raw template contents
|
||||
*/
|
||||
@SuppressWarnings({"java:S112"})
|
||||
// ignored rule java:S112 as RuntimeException is used to match previous exception type
|
||||
public String readTemplate(String name) {
|
||||
if (name == null || name.contains("..")) {
|
||||
throw new IllegalArgumentException("Template location must be constrained to template directory.");
|
||||
}
|
||||
try {
|
||||
Reader reader = getTemplateReader(name);
|
||||
if (reader == null) {
|
||||
@@ -122,12 +118,15 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
||||
throw new RuntimeException("can't load template " + name);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"squid:S2095", "java:S112"})
|
||||
// ignored rule squid:S2095 as used in the CLI and it's required to return a reader
|
||||
// ignored rule java:S112 as RuntimeException is used to match previous exception type
|
||||
@SuppressWarnings("squid:S2095")
|
||||
// ignored rule as used in the CLI and it's required to return a reader
|
||||
public Reader getTemplateReader(String name) {
|
||||
InputStream is = null;
|
||||
try {
|
||||
InputStream is = getInputStream(name);
|
||||
is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
|
||||
if (is == null) {
|
||||
is = new FileInputStream(new File(name)); // May throw but never return a null value
|
||||
}
|
||||
return new InputStreamReader(is, StandardCharsets.UTF_8);
|
||||
} catch (FileNotFoundException e) {
|
||||
LOGGER.error(e.getMessage());
|
||||
@@ -135,18 +134,6 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private InputStream getInputStream(String name) throws FileNotFoundException {
|
||||
InputStream is;
|
||||
is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
|
||||
if (is == null) {
|
||||
if (name == null || name.contains("..")) {
|
||||
throw new IllegalArgumentException("Template location must be constrained to template directory.");
|
||||
}
|
||||
is = new FileInputStream(new File(name)); // May throw but never return a null value
|
||||
}
|
||||
return is;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes data to a compiled template
|
||||
*
|
||||
@@ -158,32 +145,18 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
||||
*/
|
||||
@Override
|
||||
public File write(Map<String, Object> data, String template, File target) throws IOException {
|
||||
if (this.engineAdapter.handlesFile(template)) {
|
||||
// Only pass files with valid endings through template engine
|
||||
String templateContent = this.engineAdapter.compileTemplate(this, data, template);
|
||||
return writeToFile(target.getPath(), templateContent);
|
||||
} else {
|
||||
// Do a straight copy of the file if not listed as supported by the template engine.
|
||||
InputStream is;
|
||||
try {
|
||||
// look up the file using the same template resolution logic the adapters would use.
|
||||
String fullTemplatePath = getFullTemplateFile(template);
|
||||
is = getInputStream(fullTemplatePath);
|
||||
} catch (TemplateNotFoundException ex) {
|
||||
is = new FileInputStream(Paths.get(template).toFile());
|
||||
}
|
||||
return writeToFile(target.getAbsolutePath(), IOUtils.toByteArray(is));
|
||||
}
|
||||
String templateContent = this.engineAdapter.compileTemplate(this, data, template);
|
||||
return writeToFile(target.getPath(), templateContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ignore(Path path, String context) {
|
||||
LOGGER.info("Ignored {} ({})", path, context);
|
||||
LOGGER.info("Ignored {} ({})", path.toString(), context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void skip(Path path, String context) {
|
||||
LOGGER.info("Skipped {} ({})", path, context);
|
||||
LOGGER.info("Skipped {} ({})", path.toString(), context);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,23 +189,23 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
||||
try {
|
||||
tempFile = writeToFileRaw(tempFilename, contents);
|
||||
if (!filesEqual(tempFile, outputFile)) {
|
||||
LOGGER.info("writing file {}", filename);
|
||||
LOGGER.info("writing file " + filename);
|
||||
Files.move(tempFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
tempFile = null;
|
||||
} else {
|
||||
LOGGER.info("skipping unchanged file {}", filename);
|
||||
LOGGER.info("skipping unchanged file " + filename);
|
||||
}
|
||||
} finally {
|
||||
if (tempFile != null && tempFile.exists()) {
|
||||
try {
|
||||
Files.delete(tempFile.toPath());
|
||||
tempFile.delete();
|
||||
} catch (Exception ex) {
|
||||
LOGGER.error("Error removing temporary file {}", tempFile, ex);
|
||||
LOGGER.error("Error removing temporary file " + tempFile, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
LOGGER.info("writing file {}", filename);
|
||||
LOGGER.info("writing file " + filename);
|
||||
outputFile = writeToFileRaw(filename, contents);
|
||||
}
|
||||
|
||||
@@ -243,7 +216,7 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
||||
// Use Paths.get here to normalize path (for Windows file separator, space escaping on Linux/Mac, etc)
|
||||
File output = Paths.get(filename).toFile();
|
||||
if (this.options.isSkipOverwrite() && output.exists()) {
|
||||
LOGGER.info("skip overwrite of file {}", filename);
|
||||
LOGGER.info("skip overwrite of file " + filename);
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,11 +22,6 @@ import java.util.Locale;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
public class TemplatingEngineLoader {
|
||||
private TemplatingEngineLoader() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
@SuppressWarnings({"java:S112"}) // ignore java:S112 as generic RuntimeException is acceptable here
|
||||
public static TemplatingEngineAdapter byIdentifier(String id) {
|
||||
ServiceLoader<TemplatingEngineAdapter> loader = ServiceLoader.load(TemplatingEngineAdapter.class, TemplatingEngineLoader.class.getClassLoader());
|
||||
|
||||
@@ -42,7 +37,7 @@ public class TemplatingEngineLoader {
|
||||
// Attempt to load skipping SPI
|
||||
return (TemplatingEngineAdapter) Class.forName(id).getDeclaredConstructor().newInstance();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(String.format(Locale.ROOT, "Couldn't load template engine adapter %s. Available options: %n%s", id, sb.toString()), e);
|
||||
throw new RuntimeException(String.format(Locale.ROOT, "Couldn't load template engine adapter %s. Available options: \n%s", id, sb.toString()), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.openapitools.codegen.*;
|
||||
import org.openapitools.codegen.api.TemplateDefinition;
|
||||
import org.openapitools.codegen.api.TemplatingEngineAdapter;
|
||||
import org.openapitools.codegen.auth.AuthParser;
|
||||
import org.openapitools.codegen.utils.ModelUtils;
|
||||
@@ -73,8 +72,6 @@ public class CodegenConfigurator {
|
||||
private Map<String, String> serverVariables = new HashMap<>();
|
||||
private String auth;
|
||||
|
||||
private List<TemplateDefinition> userDefinedTemplates = new ArrayList<>();
|
||||
|
||||
public CodegenConfigurator() {
|
||||
|
||||
}
|
||||
@@ -89,7 +86,6 @@ public class CodegenConfigurator {
|
||||
|
||||
GeneratorSettings generatorSettings = settings.getGeneratorSettings();
|
||||
WorkflowSettings workflowSettings = settings.getWorkflowSettings();
|
||||
List<TemplateDefinition> userDefinedTemplateSettings = settings.getFiles();
|
||||
|
||||
// We copy "cached" properties into configurator so it is appropriately configured with all settings in external files.
|
||||
// FIXME: target is to eventually move away from CodegenConfigurator properties except gen/workflow settings.
|
||||
@@ -124,10 +120,6 @@ public class CodegenConfigurator {
|
||||
configurator.generatorSettingsBuilder = GeneratorSettings.newBuilder(generatorSettings);
|
||||
configurator.workflowSettingsBuilder = WorkflowSettings.newBuilder(workflowSettings);
|
||||
|
||||
if (userDefinedTemplateSettings != null) {
|
||||
configurator.userDefinedTemplates.addAll(userDefinedTemplateSettings);
|
||||
}
|
||||
|
||||
return configurator;
|
||||
}
|
||||
return null;
|
||||
@@ -612,8 +604,7 @@ public class CodegenConfigurator {
|
||||
}
|
||||
|
||||
ClientOptInput input = new ClientOptInput()
|
||||
.config(config)
|
||||
.userDefinedTemplates(userDefinedTemplates);
|
||||
.config(config);
|
||||
|
||||
return input.openAPI((OpenAPI)context.getSpecDocument());
|
||||
}
|
||||
|
||||
@@ -2,21 +2,19 @@ package org.openapitools.codegen.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAnySetter;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openapitools.codegen.api.TemplateDefinition;
|
||||
import org.openapitools.codegen.api.TemplateFileType;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Represents a serialization helper of {@link org.openapitools.codegen.config.GeneratorSettings} and {@link org.openapitools.codegen.config.WorkflowSettings}. When used to deserialize any available Jackson binding input,
|
||||
* this will accumulate any "unknown properties" into {@link org.openapitools.codegen.config.GeneratorSettings#getAdditionalProperties()} as a side effect of calling
|
||||
* {@link org.openapitools.codegen.config.DynamicSettings#getGeneratorSettings()}.
|
||||
* Represents a serialization helper of {@link GeneratorSettings} and {@link WorkflowSettings}. When used to deserialize any available Jackson binding input,
|
||||
* this will accumulate any "unknown properties" into {@link GeneratorSettings#getAdditionalProperties()} as a side effect of calling
|
||||
* {@link DynamicSettings#getGeneratorSettings()}.
|
||||
*/
|
||||
@SuppressWarnings({"unused", "WeakerAccess"})
|
||||
public class DynamicSettings {
|
||||
@@ -32,33 +30,7 @@ public class DynamicSettings {
|
||||
private WorkflowSettings workflowSettings;
|
||||
|
||||
/**
|
||||
* Gets the list of template files allowing user redefinition and addition of templating files
|
||||
*
|
||||
* @return A list of template files
|
||||
*/
|
||||
public List<TemplateDefinition> getFiles() {
|
||||
if (files == null) return new ArrayList<>();
|
||||
|
||||
return files.entrySet().stream().map(kvp -> {
|
||||
TemplateDefinition file = kvp.getValue();
|
||||
String templateFile = kvp.getKey();
|
||||
String destination = file.getDestinationFilename();
|
||||
if (TemplateFileType.SupportingFiles.equals(file.getTemplateType()) && StringUtils.isBlank(destination)) {
|
||||
// this special case allows definitions such as LICENSE:{}
|
||||
destination = templateFile;
|
||||
}
|
||||
TemplateDefinition definition = new TemplateDefinition(templateFile, file.getFolder(), destination);
|
||||
definition.setTemplateType(file.getTemplateType());
|
||||
return definition;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
|
||||
@JsonProperty("files")
|
||||
private Map<String, TemplateDefinition> files;
|
||||
|
||||
/**
|
||||
* Gets the {@link org.openapitools.codegen.config.GeneratorSettings} included in the config object.
|
||||
* Gets the {@link GeneratorSettings} included in the config object.
|
||||
*
|
||||
* @return A new instance of settings
|
||||
*/
|
||||
@@ -75,7 +47,7 @@ public class DynamicSettings {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link org.openapitools.codegen.config.WorkflowSettings} included in the config object.
|
||||
* Gets the {@link WorkflowSettings} included in the config object.
|
||||
*
|
||||
* @return A new instance of settings
|
||||
*/
|
||||
@@ -85,9 +57,6 @@ public class DynamicSettings {
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Constructor for DynamicSettings.</p>
|
||||
*/
|
||||
@JsonCreator
|
||||
public DynamicSettings() { }
|
||||
|
||||
|
||||
@@ -42,7 +42,6 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
|
||||
protected boolean withXml = false;
|
||||
protected boolean enumClassPrefix = false;
|
||||
protected boolean structPrefix = false;
|
||||
protected boolean generateInterfaces = false;
|
||||
|
||||
protected String packageName = "openapi";
|
||||
protected Set<String> numberTypes;
|
||||
@@ -631,7 +630,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
|
||||
}
|
||||
}
|
||||
|
||||
if (this instanceof GoClientCodegen && model.isEnum) {
|
||||
if (this instanceof GoClientExperimentalCodegen && model.isEnum) {
|
||||
imports.add(createMapping("import", "fmt"));
|
||||
}
|
||||
|
||||
@@ -781,10 +780,6 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
|
||||
this.structPrefix = structPrefix;
|
||||
}
|
||||
|
||||
public void setGenerateInterfaces(boolean generateInterfaces) {
|
||||
this.generateInterfaces = generateInterfaces;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDefaultValue(Schema schema) {
|
||||
if (schema.getDefault() != null) {
|
||||
|
||||
@@ -24,7 +24,6 @@ import io.swagger.v3.oas.models.PathItem;
|
||||
import io.swagger.v3.oas.models.media.ArraySchema;
|
||||
import io.swagger.v3.oas.models.media.ComposedSchema;
|
||||
import io.swagger.v3.oas.models.media.Schema;
|
||||
import io.swagger.v3.oas.models.media.StringSchema;
|
||||
import io.swagger.v3.oas.models.servers.Server;
|
||||
import io.swagger.v3.parser.util.SchemaTypeUtil;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
@@ -38,10 +37,11 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.openapitools.codegen.utils.StringUtils.*;
|
||||
|
||||
@@ -59,10 +59,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
public static final String SUPPORT_JAVA6 = "supportJava6";
|
||||
public static final String DISABLE_HTML_ESCAPING = "disableHtmlEscaping";
|
||||
public static final String BOOLEAN_GETTER_PREFIX = "booleanGetterPrefix";
|
||||
public static final String IGNORE_ANYOF_IN_ENUM = "ignoreAnyOfInEnum";
|
||||
public static final String ADDITIONAL_MODEL_TYPE_ANNOTATIONS = "additionalModelTypeAnnotations";
|
||||
public static final String DISCRIMINATOR_CASE_SENSITIVE = "discriminatorCaseSensitive";
|
||||
public static final String OPENAPI_NULLABLE = "openApiNullable";
|
||||
|
||||
protected String dateLibrary = "threetenbp";
|
||||
protected boolean supportAsync = false;
|
||||
@@ -97,13 +95,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
protected boolean supportJava6 = false;
|
||||
protected boolean disableHtmlEscaping = false;
|
||||
protected String booleanGetterPrefix = "get";
|
||||
protected boolean ignoreAnyOfInEnum = false;
|
||||
protected String parentGroupId = "";
|
||||
protected String parentArtifactId = "";
|
||||
protected String parentVersion = "";
|
||||
protected boolean parentOverridden = false;
|
||||
protected List<String> additionalModelTypeAnnotations = new LinkedList<>();
|
||||
protected boolean openApiNullable = true;
|
||||
|
||||
public AbstractJavaCodegen() {
|
||||
super();
|
||||
@@ -221,9 +217,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
|
||||
cliOptions.add(CliOption.newBoolean(DISABLE_HTML_ESCAPING, "Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)", disableHtmlEscaping));
|
||||
cliOptions.add(CliOption.newString(BOOLEAN_GETTER_PREFIX, "Set booleanGetterPrefix").defaultValue(this.getBooleanGetterPrefix()));
|
||||
cliOptions.add(CliOption.newBoolean(IGNORE_ANYOF_IN_ENUM, "Ignore anyOf keyword in enum", ignoreAnyOfInEnum));
|
||||
cliOptions.add(CliOption.newString(ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "Additional annotations for model type(class level annotations)"));
|
||||
cliOptions.add(CliOption.newBoolean(OPENAPI_NULLABLE, "Enable OpenAPI Jackson Nullable library", this.openApiNullable));
|
||||
|
||||
cliOptions.add(CliOption.newString(CodegenConstants.PARENT_GROUP_ID, CodegenConstants.PARENT_GROUP_ID_DESC));
|
||||
cliOptions.add(CliOption.newString(CodegenConstants.PARENT_ARTIFACT_ID, CodegenConstants.PARENT_ARTIFACT_ID_DESC));
|
||||
@@ -261,11 +255,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
}
|
||||
additionalProperties.put(BOOLEAN_GETTER_PREFIX, booleanGetterPrefix);
|
||||
|
||||
if (additionalProperties.containsKey(IGNORE_ANYOF_IN_ENUM)) {
|
||||
this.setIgnoreAnyOfInEnum(Boolean.valueOf(additionalProperties.get(IGNORE_ANYOF_IN_ENUM).toString()));
|
||||
}
|
||||
additionalProperties.put(IGNORE_ANYOF_IN_ENUM, ignoreAnyOfInEnum);
|
||||
|
||||
if (additionalProperties.containsKey(ADDITIONAL_MODEL_TYPE_ANNOTATIONS)) {
|
||||
String additionalAnnotationsList = additionalProperties.get(ADDITIONAL_MODEL_TYPE_ANNOTATIONS).toString();
|
||||
|
||||
@@ -423,11 +412,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
}
|
||||
additionalProperties.put(WITH_XML, withXml);
|
||||
|
||||
if (additionalProperties.containsKey(OPENAPI_NULLABLE)) {
|
||||
this.setOpenApiNullable(Boolean.valueOf(additionalProperties.get(OPENAPI_NULLABLE).toString()));
|
||||
}
|
||||
additionalProperties.put(OPENAPI_NULLABLE, openApiNullable);
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.PARENT_GROUP_ID)) {
|
||||
this.setParentGroupId((String) additionalProperties.get(CodegenConstants.PARENT_GROUP_ID));
|
||||
}
|
||||
@@ -773,23 +757,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Schema p) {
|
||||
Schema<?> schema = ModelUtils.unaliasSchema(this.openAPI, p);
|
||||
Schema<?> target = ModelUtils.isGenerateAliasAsModel() ? p : schema;
|
||||
if (ModelUtils.isArraySchema(target)) {
|
||||
Schema<?> items = getSchemaItems((ArraySchema) schema);
|
||||
return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
|
||||
} else if (ModelUtils.isMapSchema(target)) {
|
||||
if (ModelUtils.isArraySchema(p)) {
|
||||
Schema<?> items = getSchemaItems((ArraySchema) p);
|
||||
return getSchemaType(p) + "<" + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items)) + ">";
|
||||
} else if (ModelUtils.isMapSchema(p) && !ModelUtils.isComposedSchema(p)) {
|
||||
// Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
|
||||
// additionalproperties: true
|
||||
Schema<?> inner = getAdditionalProperties(target);
|
||||
if (inner == null) {
|
||||
LOGGER.error("`{}` (map property) does not have a proper inner type defined. Default to type:string", p.getName());
|
||||
inner = new StringSchema().description("TODO default missing map inner type to string");
|
||||
p.setAdditionalProperties(inner);
|
||||
}
|
||||
return getSchemaType(target) + "<String, " + getTypeDeclaration(inner) + ">";
|
||||
Schema<?> inner = getSchemaAdditionalProperties(p);
|
||||
return getSchemaType(p) + "<String, " + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + ">";
|
||||
}
|
||||
return super.getTypeDeclaration(target);
|
||||
return super.getTypeDeclaration(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1179,28 +1156,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
}
|
||||
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
|
||||
|
||||
if (ignoreAnyOfInEnum) {
|
||||
// Alter OpenAPI schemas ignore anyOf keyword if it consist of an enum. Example:
|
||||
// anyOf:
|
||||
// - type: string
|
||||
// enum:
|
||||
// - ENUM_A
|
||||
// - ENUM_B
|
||||
Stream.concat(
|
||||
Stream.of(openAPI.getComponents().getSchemas()),
|
||||
openAPI.getComponents().getSchemas().values().stream()
|
||||
.filter(schema -> schema.getProperties() != null)
|
||||
.map(Schema::getProperties))
|
||||
.forEach(schemas -> schemas.replaceAll(
|
||||
(name, s) -> Stream.of(s)
|
||||
.filter(schema -> schema instanceof ComposedSchema)
|
||||
.map(schema -> (ComposedSchema) schema)
|
||||
.filter(schema -> Objects.nonNull(schema.getAnyOf()))
|
||||
.flatMap(schema -> schema.getAnyOf().stream())
|
||||
.filter(schema -> Objects.nonNull(schema.getEnum()))
|
||||
.findFirst()
|
||||
.orElse((Schema) s)));
|
||||
}
|
||||
}
|
||||
|
||||
private static String getAccept(OpenAPI openAPI, Operation operation) {
|
||||
@@ -1552,18 +1507,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
this.booleanGetterPrefix = booleanGetterPrefix;
|
||||
}
|
||||
|
||||
public void setIgnoreAnyOfInEnum(boolean ignoreAnyOfInEnum) {
|
||||
this.ignoreAnyOfInEnum = ignoreAnyOfInEnum;
|
||||
}
|
||||
|
||||
public boolean isOpenApiNullable() {
|
||||
return openApiNullable;
|
||||
}
|
||||
|
||||
public void setOpenApiNullable(final boolean openApiNullable) {
|
||||
this.openApiNullable = openApiNullable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeQuotationMark(String input) {
|
||||
// remove " to avoid code injection
|
||||
|
||||
@@ -17,11 +17,9 @@
|
||||
|
||||
package org.openapitools.codegen.languages;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.Operation;
|
||||
import io.swagger.v3.oas.models.PathItem;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openapitools.codegen.*;
|
||||
import org.openapitools.codegen.languages.features.BeanValidationFeatures;
|
||||
import org.openapitools.codegen.utils.URLPathUtils;
|
||||
@@ -32,10 +30,10 @@ import java.io.File;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
|
||||
import static org.openapitools.codegen.utils.StringUtils.camelize;
|
||||
|
||||
public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
|
||||
public static final String SERVER_PORT = "serverPort";
|
||||
public static final String USE_TAGS = "useTags";
|
||||
|
||||
/**
|
||||
* Name of the sub-directory in "src/main/resource" where to find the
|
||||
* Mustache template for the JAX-RS Codegen.
|
||||
@@ -45,9 +43,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
protected String testResourcesFolder = "src/test/resources";
|
||||
protected String title = "OpenAPI Server";
|
||||
protected String serverPort = "8080";
|
||||
|
||||
protected boolean useBeanValidation = true;
|
||||
protected boolean useTags = false;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
|
||||
|
||||
@@ -76,7 +72,6 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
cliOptions.add(new CliOption("title", "a title describing the application").defaultValue(title));
|
||||
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations",useBeanValidation));
|
||||
cliOptions.add(new CliOption(SERVER_PORT, "The port on which the server should be started").defaultValue(serverPort));
|
||||
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
|
||||
}
|
||||
|
||||
|
||||
@@ -98,32 +93,11 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
|
||||
setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(USE_TAGS)) {
|
||||
setUseTags(convertPropertyToBoolean(USE_TAGS));
|
||||
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
|
||||
}
|
||||
|
||||
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
|
||||
final String basePath = StringUtils.substringBefore(StringUtils.removeStart(resourcePath, "/"), "/");
|
||||
if (!StringUtils.isEmpty(basePath)) {
|
||||
co.subresourceOperation = !co.path.isEmpty();
|
||||
}
|
||||
if (useTags) {
|
||||
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
|
||||
} else {
|
||||
co.baseName = basePath;
|
||||
if (StringUtils.isEmpty(co.baseName) || StringUtils.containsAny(co.baseName, "{", "}")) {
|
||||
co.baseName = "default";
|
||||
}
|
||||
final List<CodegenOperation> opList = operations.computeIfAbsent(co.baseName, k -> new ArrayList<>());
|
||||
opList.add(co);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -177,8 +151,9 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
static Map<String, Object> jaxrsPostProcessOperations(Map<String, Object> objs) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
String commonPath = null;
|
||||
if (operations != null) {
|
||||
String commonBaseName = null;
|
||||
boolean baseNameEquals = true;
|
||||
@SuppressWarnings("unchecked")
|
||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
||||
for (CodegenOperation operation : ops) {
|
||||
@@ -248,18 +223,24 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
} else if ("map".equals(operation.returnContainer)) {
|
||||
operation.returnContainer = "Map";
|
||||
}
|
||||
|
||||
if (commonPath == null) {
|
||||
commonPath = operation.path;
|
||||
} else {
|
||||
commonPath = getCommonPath(commonPath, operation.path);
|
||||
|
||||
if(commonBaseName == null) {
|
||||
commonBaseName = operation.baseName;
|
||||
} else if(!commonBaseName.equals(operation.baseName)) {
|
||||
baseNameEquals = false;
|
||||
}
|
||||
}
|
||||
for (CodegenOperation co : ops) {
|
||||
co.path = StringUtils.removeStart(co.path, commonPath);
|
||||
co.subresourceOperation = co.path.length() > 1;
|
||||
if(baseNameEquals) {
|
||||
objs.put("commonPath", commonBaseName);
|
||||
} else {
|
||||
for (CodegenOperation operation : ops) {
|
||||
if(operation.baseName != null) {
|
||||
operation.path = "/" + operation.baseName + operation.path;
|
||||
operation.baseName = null;
|
||||
}
|
||||
}
|
||||
objs.put("commonPath", null);
|
||||
}
|
||||
objs.put("commonPath", "/".equals(commonPath) ? StringUtils.EMPTY : commonPath);
|
||||
}
|
||||
return objs;
|
||||
}
|
||||
@@ -270,7 +251,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
if (computed.length() > 0) {
|
||||
computed = sanitizeName(computed);
|
||||
}
|
||||
return super.toApiName(computed);
|
||||
return super.toApiName(computed);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -292,19 +273,6 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String getCommonPath(String path1, String path2) {
|
||||
final String[] parts1 = StringUtils.split(path1, "/");
|
||||
final String[] parts2 = StringUtils.split(path2, "/");
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (int i = 0; i < Math.min(parts1.length, parts2.length); i++) {
|
||||
if (!parts1[i].equals(parts2[i])) {
|
||||
break;
|
||||
}
|
||||
builder.append("/").append(parts1[i]);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private String implFileFolder(String output) {
|
||||
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
|
||||
}
|
||||
@@ -313,8 +281,5 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
|
||||
this.useBeanValidation = useBeanValidation;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setUseTags(boolean useTags) {
|
||||
this.useTags = useTags;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -771,9 +771,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
|
||||
@Override
|
||||
protected boolean needToImport(String type) {
|
||||
// provides extra protection against improperly trying to import language primitives and java types
|
||||
boolean imports = !type.startsWith("kotlin.") && !type.startsWith("java.") &&
|
||||
!defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type) &&
|
||||
!type.contains(".");
|
||||
boolean imports = !type.startsWith("kotlin.") && !type.startsWith("java.") && !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type);
|
||||
return imports;
|
||||
}
|
||||
|
||||
|
||||
@@ -690,13 +690,13 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
|
||||
case original:
|
||||
return name;
|
||||
case camelCase:
|
||||
return camelize(underscore(name), true);
|
||||
return camelize(name, true);
|
||||
case PascalCase:
|
||||
return camelize(underscore(name));
|
||||
return camelize(name);
|
||||
case snake_case:
|
||||
return underscore(name);
|
||||
case UPPERCASE:
|
||||
return underscore(name).toUpperCase(Locale.ROOT);
|
||||
return name.toUpperCase(Locale.ROOT);
|
||||
default:
|
||||
throw new IllegalArgumentException("Unsupported enum property naming: '" + name);
|
||||
}
|
||||
|
||||
@@ -97,10 +97,10 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
|
||||
String srcPrefix = "src" + File.separator;
|
||||
String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage);
|
||||
String clientPrefix = srcPrefix + "client" + File.separator + toFilename(modelPackage);
|
||||
supportingFiles.add(new SupportingFile("model-spec.mustache", "", modelPrefix + "-models.ads"));
|
||||
supportingFiles.add(new SupportingFile("model-body.mustache", "", modelPrefix + "-models.adb"));
|
||||
supportingFiles.add(new SupportingFile("client-spec.mustache", "", clientPrefix + "-clients.ads"));
|
||||
supportingFiles.add(new SupportingFile("client-body.mustache", "", clientPrefix + "-clients.adb"));
|
||||
supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads"));
|
||||
supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb"));
|
||||
supportingFiles.add(new SupportingFile("client-spec.mustache", null, clientPrefix + "-clients.ads"));
|
||||
supportingFiles.add(new SupportingFile("client-body.mustache", null, clientPrefix + "-clients.adb"));
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) {
|
||||
projectName = (String) additionalProperties.get(CodegenConstants.PROJECT_NAME);
|
||||
@@ -125,20 +125,20 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
|
||||
additionalProperties.put("isServer", false);
|
||||
additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName);
|
||||
|
||||
String[] names = this.modelPackage.split("\\.");
|
||||
String names[] = this.modelPackage.split("\\.");
|
||||
String pkgName = names[0];
|
||||
additionalProperties.put("packageLevel1", pkgName);
|
||||
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", "",
|
||||
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null,
|
||||
"src" + File.separator + toFilename(names[0]) + ".ads"));
|
||||
if (names.length > 1) {
|
||||
String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads";
|
||||
pkgName = names[0] + "." + names[1];
|
||||
additionalProperties.put("packageLevel2", pkgName);
|
||||
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", "",
|
||||
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null,
|
||||
"src" + File.separator + fileName));
|
||||
}
|
||||
pkgName = this.modelPackage;
|
||||
supportingFiles.add(new SupportingFile("client.mustache", "",
|
||||
supportingFiles.add(new SupportingFile("client.mustache", null,
|
||||
"src" + File.separator + toFilename(pkgName) + "-client.adb"));
|
||||
additionalProperties.put("packageName", toFilename(pkgName));
|
||||
|
||||
|
||||
@@ -92,12 +92,12 @@ public class AdaServerCodegen extends AbstractAdaCodegen implements CodegenConfi
|
||||
String serverPrefix = srcPrefix + "server" + File.separator + toFilename(modelPackage);
|
||||
String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage);
|
||||
String implPrefix = srcPrefix + toFilename(modelPackage);
|
||||
supportingFiles.add(new SupportingFile("model-spec.mustache", "", modelPrefix + "-models.ads"));
|
||||
supportingFiles.add(new SupportingFile("model-body.mustache", "", modelPrefix + "-models.adb"));
|
||||
supportingFiles.add(new SupportingFile("server-skeleton-spec.mustache", "", serverPrefix + "-skeletons.ads"));
|
||||
supportingFiles.add(new SupportingFile("server-skeleton-body.mustache", "", serverPrefix + "-skeletons.adb"));
|
||||
supportingFiles.add(new SupportingFile("server-spec.mustache", "", implPrefix + "-servers.ads"));
|
||||
supportingFiles.add(new SupportingFile("server-body.mustache", "", implPrefix + "-servers.adb"));
|
||||
supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads"));
|
||||
supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb"));
|
||||
supportingFiles.add(new SupportingFile("server-skeleton-spec.mustache", null, serverPrefix + "-skeletons.ads"));
|
||||
supportingFiles.add(new SupportingFile("server-skeleton-body.mustache", null, serverPrefix + "-skeletons.adb"));
|
||||
supportingFiles.add(new SupportingFile("server-spec.mustache", null, implPrefix + "-servers.ads"));
|
||||
supportingFiles.add(new SupportingFile("server-body.mustache", null, implPrefix + "-servers.adb"));
|
||||
|
||||
supportingFiles.add(new SupportingFile("openapi.mustache", "web" + File.separator + "swagger", "openapi.json"));
|
||||
|
||||
@@ -128,17 +128,17 @@ public class AdaServerCodegen extends AbstractAdaCodegen implements CodegenConfi
|
||||
String names[] = this.modelPackage.split("\\.");
|
||||
String pkgName = names[0];
|
||||
additionalProperties.put("packageLevel1", pkgName);
|
||||
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", "",
|
||||
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null,
|
||||
"src" + File.separator + toFilename(names[0]) + ".ads"));
|
||||
if (names.length > 1) {
|
||||
String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads";
|
||||
pkgName = names[0] + "." + names[1];
|
||||
additionalProperties.put("packageLevel2", pkgName);
|
||||
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", "",
|
||||
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null,
|
||||
"src" + File.separator + fileName));
|
||||
}
|
||||
pkgName = this.modelPackage;
|
||||
supportingFiles.add(new SupportingFile("server.mustache", "",
|
||||
supportingFiles.add(new SupportingFile("server.mustache", null,
|
||||
"src" + File.separator + toFilename(pkgName) + "-server.adb"));
|
||||
additionalProperties.put("packageName", toFilename(pkgName));
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ import io.swagger.v3.oas.models.media.Schema;
|
||||
import org.openapitools.codegen.*;
|
||||
import org.openapitools.codegen.meta.features.*;
|
||||
import org.openapitools.codegen.utils.ModelUtils;
|
||||
import org.openapitools.codegen.utils.ProcessUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@@ -611,9 +610,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
|
||||
supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs"));
|
||||
supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs"));
|
||||
supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs"));
|
||||
if (ProcessUtils.hasHttpSignatureMethods(openAPI)) {
|
||||
supportingFiles.add(new SupportingFile("HTTPSigningConfiguration.mustache", clientPackageDir, "HTTPSigningConfiguration.cs"));
|
||||
}
|
||||
if (supportsAsync) {
|
||||
supportingFiles.add(new SupportingFile("IAsynchronousClient.mustache", clientPackageDir, "IAsynchronousClient.cs"));
|
||||
}
|
||||
|
||||
@@ -17,36 +17,29 @@
|
||||
|
||||
package org.openapitools.codegen.languages;
|
||||
|
||||
import io.swagger.v3.oas.models.media.Schema;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openapitools.codegen.*;
|
||||
import org.openapitools.codegen.meta.GeneratorMetadata;
|
||||
import org.openapitools.codegen.meta.Stability;
|
||||
import org.openapitools.codegen.CliOption;
|
||||
import org.openapitools.codegen.CodegenConstants;
|
||||
import org.openapitools.codegen.CodegenType;
|
||||
import org.openapitools.codegen.SupportingFile;
|
||||
import org.openapitools.codegen.meta.features.*;
|
||||
import org.openapitools.codegen.utils.ModelUtils;
|
||||
import org.openapitools.codegen.utils.ProcessUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
|
||||
import static org.openapitools.codegen.utils.StringUtils.camelize;
|
||||
import java.util.EnumSet;
|
||||
|
||||
public class GoClientCodegen extends AbstractGoCodegen {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class);
|
||||
|
||||
protected String packageVersion = "1.0.0";
|
||||
protected String apiDocPath = "docs/";
|
||||
protected String modelDocPath = "docs/";
|
||||
protected boolean isGoSubmodule = false;
|
||||
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
|
||||
public static final String WITH_XML = "withXml";
|
||||
public static final String STRUCT_PREFIX = "structPrefix";
|
||||
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
|
||||
public static final String GENERATE_INTERFACES = "generateInterfaces";
|
||||
protected String goImportAlias = "openapiclient";
|
||||
protected boolean isGoSubmodule = false;
|
||||
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
|
||||
|
||||
public GoClientCodegen() {
|
||||
super();
|
||||
@@ -80,92 +73,34 @@ public class GoClientCodegen extends AbstractGoCodegen {
|
||||
)
|
||||
);
|
||||
|
||||
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.STABLE).build();
|
||||
|
||||
outputFolder = "generated-code/go";
|
||||
embeddedTemplateDir = templateDir = "go";
|
||||
usesOptionals = false;
|
||||
|
||||
apiTemplateFiles.put("api.mustache", ".go");
|
||||
modelTemplateFiles.put("model.mustache", ".go");
|
||||
apiTemplateFiles.put("api.mustache", ".go");
|
||||
|
||||
modelDocTemplateFiles.put("model_doc.mustache", ".md");
|
||||
apiDocTemplateFiles.put("api_doc.mustache", ".md");
|
||||
|
||||
embeddedTemplateDir = templateDir = "go";
|
||||
|
||||
// default HIDE_GENERATION_TIMESTAMP to true
|
||||
hideGenerationTimestamp = Boolean.TRUE;
|
||||
|
||||
cliOptions.add(CliOption.newBoolean(CodegenConstants.IS_GO_SUBMODULE, CodegenConstants.IS_GO_SUBMODULE_DESC));
|
||||
cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs"));
|
||||
cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)"));
|
||||
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
|
||||
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
|
||||
cliOptions.add(CliOption.newBoolean(WITH_AWSV4_SIGNATURE, "whether to include AWS v4 signature support"));
|
||||
cliOptions.add(CliOption.newBoolean(GENERATE_INTERFACES, "Generate interfaces for api classes"));
|
||||
|
||||
// option to change the order of form/body parameter
|
||||
cliOptions.add(CliOption.newBoolean(
|
||||
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS,
|
||||
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC)
|
||||
.defaultValue(Boolean.FALSE.toString()));
|
||||
|
||||
cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC).defaultValue("false"));
|
||||
// option to change how we process + set the data in the 'additionalProperties' keyword.
|
||||
CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean(
|
||||
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT,
|
||||
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString());
|
||||
Map<String, String> disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>();
|
||||
disallowAdditionalPropertiesIfNotPresentOpts.put("false",
|
||||
"The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.");
|
||||
disallowAdditionalPropertiesIfNotPresentOpts.put("true",
|
||||
"when the 'additionalProperties' keyword is not present in a schema, " +
|
||||
"the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. " +
|
||||
"Note: this mode is not compliant with the JSON schema specification. " +
|
||||
"This is the original openapi-generator behavior.");
|
||||
disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts);
|
||||
cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt);
|
||||
this.setDisallowAdditionalPropertiesIfNotPresent(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the
|
||||
* generator to select the library with the -g flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "go";
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see org.openapitools.codegen.CodegenType
|
||||
*/
|
||||
@Override
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toGetter(String name) {
|
||||
return "Get" + getterAndSetterCapitalize(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
@Override
|
||||
public String getHelp() {
|
||||
return "Generates a Go client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
this.setLegacyDiscriminatorBehavior(false);
|
||||
super.processOpts();
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
|
||||
@@ -189,6 +124,22 @@ public class GoClientCodegen extends AbstractGoCodegen {
|
||||
modelPackage = packageName;
|
||||
apiPackage = packageName;
|
||||
|
||||
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
|
||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
|
||||
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
|
||||
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
|
||||
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
|
||||
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
|
||||
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
|
||||
|
||||
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
|
||||
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
|
||||
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(WITH_AWSV4_SIGNATURE)) {
|
||||
setWithAWSV4Signature(Boolean.parseBoolean(additionalProperties.get(WITH_AWSV4_SIGNATURE).toString()));
|
||||
additionalProperties.put(WITH_AWSV4_SIGNATURE, withAWSV4Signature);
|
||||
@@ -213,68 +164,39 @@ public class GoClientCodegen extends AbstractGoCodegen {
|
||||
setStructPrefix(Boolean.parseBoolean(additionalProperties.get(STRUCT_PREFIX).toString()));
|
||||
additionalProperties.put(STRUCT_PREFIX, structPrefix);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(GENERATE_INTERFACES)) {
|
||||
setGenerateInterfaces(Boolean.parseBoolean(additionalProperties.get(GENERATE_INTERFACES).toString()));
|
||||
additionalProperties.put(GENERATE_INTERFACES, generateInterfaces);
|
||||
}
|
||||
|
||||
// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
|
||||
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
|
||||
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
|
||||
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
|
||||
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
|
||||
supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go"));
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey("goImportAlias")) {
|
||||
setGoImportAlias(additionalProperties.get("goImportAlias").toString());
|
||||
} else {
|
||||
additionalProperties.put("goImportAlias", goImportAlias);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
|
||||
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
|
||||
} else {
|
||||
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, getUseOneOfDiscriminatorLookup());
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) {
|
||||
this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.valueOf(additionalProperties
|
||||
.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()));
|
||||
}
|
||||
|
||||
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
|
||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
|
||||
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
|
||||
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
|
||||
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
|
||||
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
|
||||
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
|
||||
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));
|
||||
}
|
||||
|
||||
public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
|
||||
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see org.openapitools.codegen.CodegenType
|
||||
*/
|
||||
@Override
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public boolean getUseOneOfDiscriminatorLookup() {
|
||||
return this.useOneOfDiscriminatorLookup;
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the generator
|
||||
* to select the library with the -g flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "go";
|
||||
}
|
||||
|
||||
public void setGoImportAlias(String goImportAlias) {
|
||||
this.goImportAlias = goImportAlias;
|
||||
}
|
||||
|
||||
public void setPackageVersion(String packageVersion) {
|
||||
this.packageVersion = packageVersion;
|
||||
}
|
||||
|
||||
public void setIsGoSubmodule(boolean isGoSubmodule) {
|
||||
this.isGoSubmodule = isGoSubmodule;
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
@Override
|
||||
public String getHelp() {
|
||||
return "Generates a Go client library (beta).";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -311,267 +233,12 @@ public class GoClientCodegen extends AbstractGoCodegen {
|
||||
return toApiName(name);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// underscoring would also lowercase the whole name, thus losing acronyms which are in capitals
|
||||
return camelize(toModel(name, false));
|
||||
public void setPackageVersion(String packageVersion) {
|
||||
this.packageVersion = packageVersion;
|
||||
}
|
||||
|
||||
public String escapeReservedWord(String name) {
|
||||
if (this.reservedWordsMappings().containsKey(name)) {
|
||||
return this.reservedWordsMappings().get(name);
|
||||
}
|
||||
return name + '_';
|
||||
public void setIsGoSubmodule(boolean isGoSubmodule) {
|
||||
this.isGoSubmodule = isGoSubmodule;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumDefaultValue(String value, String datatype) {
|
||||
String prefix = "";
|
||||
if (enumClassPrefix) {
|
||||
prefix = datatype.toUpperCase(Locale.ROOT) + "_";
|
||||
}
|
||||
return prefix + value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCodegenPropertyEnum(CodegenProperty var) {
|
||||
// make sure the inline enums have plain defaults (e.g. string, int, float)
|
||||
String enumDefault = null;
|
||||
if (var.isEnum && var.defaultValue != null) {
|
||||
enumDefault = var.defaultValue;
|
||||
}
|
||||
super.updateCodegenPropertyEnum(var);
|
||||
if (var.isEnum && enumDefault != null) {
|
||||
var.defaultValue = enumDefault;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDefaultValue(Schema p) {
|
||||
p = ModelUtils.getReferencedSchema(this.openAPI, p);
|
||||
if (ModelUtils.isStringSchema(p)) {
|
||||
if (p.getDefault() != null) {
|
||||
return "\"" + escapeText((String) p.getDefault()) + "\"";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return super.toDefaultValue(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CodegenProperty fromProperty(String name, Schema p) {
|
||||
CodegenProperty prop = super.fromProperty(name, p);
|
||||
String cc = camelize(prop.name, true);
|
||||
if (isReservedWord(cc)) {
|
||||
cc = escapeReservedWord(cc);
|
||||
}
|
||||
prop.nameInCamelCase = cc;
|
||||
return prop;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
|
||||
// The superclass determines the list of required golang imports. The actual list of imports
|
||||
// depends on which types are used, some of which are changed in the code below (but then preserved
|
||||
// and used through x-go-base-type in templates). So super.postProcessModels
|
||||
// must be invoked at the beginning of this method.
|
||||
objs = super.postProcessModels(objs);
|
||||
|
||||
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
|
||||
|
||||
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
|
||||
for (Map<String, Object> m : models) {
|
||||
Object v = m.get("model");
|
||||
if (v instanceof CodegenModel) {
|
||||
CodegenModel model = (CodegenModel) v;
|
||||
if (model.isEnum) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (CodegenProperty param : model.vars) {
|
||||
param.vendorExtensions.put("x-go-base-type", param.dataType);
|
||||
if (!param.isNullable || param.isMapContainer || param.isListContainer ||
|
||||
param.isFreeFormObject || param.isAnyType) {
|
||||
continue;
|
||||
}
|
||||
if (param.isDateTime) {
|
||||
// Note this could have been done by adding the following line in processOpts(),
|
||||
// however, we only want to represent the DateTime object as NullableTime if
|
||||
// it's marked as nullable in the spec.
|
||||
// typeMapping.put("DateTime", "NullableTime");
|
||||
param.dataType = "NullableTime";
|
||||
} else {
|
||||
param.dataType = "Nullable" + Character.toUpperCase(param.dataType.charAt(0))
|
||||
+ param.dataType.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
// additional import for different cases
|
||||
// oneOf
|
||||
if (model.oneOf != null && !model.oneOf.isEmpty()) {
|
||||
imports.add(createMapping("import", "fmt"));
|
||||
}
|
||||
|
||||
// anyOf
|
||||
if (model.anyOf != null && !model.anyOf.isEmpty()) {
|
||||
imports.add(createMapping("import", "fmt"));
|
||||
}
|
||||
|
||||
// additionalProperties: true and parent
|
||||
if (model.isAdditionalPropertiesTrue && model.parent != null && Boolean.FALSE.equals(model.isMapModel)) {
|
||||
imports.add(createMapping("import", "reflect"));
|
||||
imports.add(createMapping("import", "strings"));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return objs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
|
||||
objs = super.postProcessOperationsWithModels(objs, allModels);
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
HashMap<String, CodegenModel> modelMaps = new HashMap<String, CodegenModel>();
|
||||
HashMap<String, Integer> processedModelMaps = new HashMap<String, Integer>();
|
||||
|
||||
for (Object o : allModels) {
|
||||
HashMap<String, Object> h = (HashMap<String, Object>) o;
|
||||
CodegenModel m = (CodegenModel) h.get("model");
|
||||
modelMaps.put(m.classname, m);
|
||||
}
|
||||
|
||||
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
|
||||
for (CodegenOperation op : operationList) {
|
||||
for (CodegenParameter p : op.allParams) {
|
||||
p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps));
|
||||
}
|
||||
}
|
||||
|
||||
processedModelMaps.clear();
|
||||
for (CodegenOperation operation : operationList) {
|
||||
for (CodegenParameter cp : operation.allParams) {
|
||||
cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps));
|
||||
}
|
||||
}
|
||||
|
||||
return objs;
|
||||
}
|
||||
|
||||
private String constructExampleCode(CodegenParameter codegenParameter, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
|
||||
if (codegenParameter.isListContainer) { // array
|
||||
return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
|
||||
} else if (codegenParameter.isMapContainer) {
|
||||
return "map[string]string{ \"Key\" = \"Value\" }";
|
||||
} else if (codegenParameter.isPrimitiveType) { // primitive type
|
||||
if (codegenParameter.isString) {
|
||||
if (StringUtils.isEmpty(codegenParameter.example)) {
|
||||
return "\"" + codegenParameter.example + "\"";
|
||||
} else {
|
||||
return "\"" + codegenParameter.paramName + "_example\"";
|
||||
}
|
||||
} else if (codegenParameter.isBoolean) { // boolean
|
||||
if (Boolean.parseBoolean(codegenParameter.example)) {
|
||||
return "true";
|
||||
} else {
|
||||
return "false";
|
||||
}
|
||||
} else if (codegenParameter.isUri) { // URL
|
||||
return "URL(string: \"https://example.com\")!";
|
||||
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
|
||||
return "Get-Date";
|
||||
} else { // numeric
|
||||
if (StringUtils.isEmpty(codegenParameter.example)) {
|
||||
return codegenParameter.example;
|
||||
} else {
|
||||
return "987";
|
||||
}
|
||||
}
|
||||
} else { // model
|
||||
// look up the model
|
||||
if (modelMaps.containsKey(codegenParameter.dataType)) {
|
||||
return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap);
|
||||
} else {
|
||||
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType);
|
||||
return "TODO";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String constructExampleCode(CodegenProperty codegenProperty, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
|
||||
if (codegenProperty.isListContainer) { // array
|
||||
return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")";
|
||||
} else if (codegenProperty.isMapContainer) { // map
|
||||
return "map[string]string{ \"Key\" = \"Value\" }";
|
||||
} else if (codegenProperty.isPrimitiveType) { // primitive type
|
||||
if (codegenProperty.isString) {
|
||||
if (StringUtils.isEmpty(codegenProperty.example)) {
|
||||
return "\"" + codegenProperty.example + "\"";
|
||||
} else {
|
||||
return "\"" + codegenProperty.name + "_example\"";
|
||||
}
|
||||
} else if (codegenProperty.isBoolean) { // boolean
|
||||
if (Boolean.parseBoolean(codegenProperty.example)) {
|
||||
return "true";
|
||||
} else {
|
||||
return "false";
|
||||
}
|
||||
} else if (codegenProperty.isUri) { // URL
|
||||
return "\"https://example.com\")!";
|
||||
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
|
||||
return "time.Now()";
|
||||
} else { // numeric
|
||||
String example;
|
||||
if (StringUtils.isEmpty(codegenProperty.example)) {
|
||||
example = codegenProperty.example;
|
||||
} else {
|
||||
example = "123";
|
||||
}
|
||||
|
||||
if (codegenProperty.isLong) {
|
||||
return "int64(" + example + ")";
|
||||
} else {
|
||||
return example;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// look up the model
|
||||
if (modelMaps.containsKey(codegenProperty.dataType)) {
|
||||
return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap);
|
||||
} else {
|
||||
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType);
|
||||
return "\"TODO\"";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String constructExampleCode(CodegenModel codegenModel, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
|
||||
String example;
|
||||
|
||||
// break infinite recursion. Return, in case a model is already processed in the current context.
|
||||
String model = codegenModel.name;
|
||||
if (processedModelMap.containsKey(model)) {
|
||||
int count = processedModelMap.get(model);
|
||||
if (count == 1) {
|
||||
processedModelMap.put(model, 2);
|
||||
} else if (count == 2) {
|
||||
return "";
|
||||
} else {
|
||||
throw new RuntimeException("Invalid count when constructing example: " + count);
|
||||
}
|
||||
} else {
|
||||
processedModelMap.put(model, 1);
|
||||
}
|
||||
|
||||
example = "" + goImportAlias + "." + codegenModel.name + "{";
|
||||
List<String> propertyExamples = new ArrayList<>();
|
||||
for (CodegenProperty codegenProperty : codegenModel.allVars) {
|
||||
propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap));
|
||||
}
|
||||
example += StringUtils.join(propertyExamples, ", ");
|
||||
example += "}";
|
||||
return example;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
/*
|
||||
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.openapitools.codegen.languages;
|
||||
|
||||
import io.swagger.v3.oas.models.media.Schema;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openapitools.codegen.*;
|
||||
import org.openapitools.codegen.meta.GeneratorMetadata;
|
||||
import org.openapitools.codegen.meta.Stability;
|
||||
import org.openapitools.codegen.utils.ModelUtils;
|
||||
import org.openapitools.codegen.utils.ProcessUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static org.openapitools.codegen.utils.StringUtils.camelize;
|
||||
|
||||
public class GoClientExperimentalCodegen extends GoClientCodegen {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(GoClientExperimentalCodegen.class);
|
||||
protected String goImportAlias = "openapiclient";
|
||||
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
|
||||
|
||||
public GoClientExperimentalCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/go-experimental";
|
||||
embeddedTemplateDir = templateDir = "go-experimental";
|
||||
|
||||
usesOptionals = false;
|
||||
|
||||
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.EXPERIMENTAL).build();
|
||||
|
||||
cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC).defaultValue("false"));
|
||||
// option to change how we process + set the data in the 'additionalProperties' keyword.
|
||||
CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean(
|
||||
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT,
|
||||
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString());
|
||||
Map<String, String> disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>();
|
||||
disallowAdditionalPropertiesIfNotPresentOpts.put("false",
|
||||
"The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.");
|
||||
disallowAdditionalPropertiesIfNotPresentOpts.put("true",
|
||||
"when the 'additionalProperties' keyword is not present in a schema, " +
|
||||
"the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. " +
|
||||
"Note: this mode is not compliant with the JSON schema specification. " +
|
||||
"This is the original openapi-generator behavior.");
|
||||
disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts);
|
||||
cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt);
|
||||
this.setDisallowAdditionalPropertiesIfNotPresent(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the
|
||||
* generator to select the library with the -g flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "go-experimental";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toGetter(String name) {
|
||||
return "Get" + getterAndSetterCapitalize(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
@Override
|
||||
public String getHelp() {
|
||||
return "Generates a Go client library (experimental and may subject to breaking changes without further notice).";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
this.setLegacyDiscriminatorBehavior(false);
|
||||
super.processOpts();
|
||||
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));
|
||||
|
||||
// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
|
||||
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
|
||||
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
|
||||
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
|
||||
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
|
||||
supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go"));
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey("goImportAlias")) {
|
||||
setGoImportAlias(additionalProperties.get("goImportAlias").toString());
|
||||
} else {
|
||||
additionalProperties.put("goImportAlias", goImportAlias);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
|
||||
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
|
||||
} else {
|
||||
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, useOneOfDiscriminatorLookup);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) {
|
||||
this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.valueOf(additionalProperties
|
||||
.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
|
||||
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
|
||||
}
|
||||
|
||||
public boolean getUseOneOfDiscriminatorLookup() {
|
||||
return this.useOneOfDiscriminatorLookup;
|
||||
}
|
||||
|
||||
public void setGoImportAlias(String goImportAlias) {
|
||||
this.goImportAlias = goImportAlias;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// underscoring would also lowercase the whole name, thus losing acronyms which are in capitals
|
||||
return camelize(toModel(name, false));
|
||||
}
|
||||
|
||||
public String escapeReservedWord(String name) {
|
||||
if (this.reservedWordsMappings().containsKey(name)) {
|
||||
return this.reservedWordsMappings().get(name);
|
||||
}
|
||||
return name + '_';
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumDefaultValue(String value, String datatype) {
|
||||
String prefix = "";
|
||||
if (enumClassPrefix) {
|
||||
prefix = datatype.toUpperCase(Locale.ROOT) + "_";
|
||||
}
|
||||
return prefix + value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCodegenPropertyEnum(CodegenProperty var) {
|
||||
// make sure the inline enums have plain defaults (e.g. string, int, float)
|
||||
String enumDefault = null;
|
||||
if (var.isEnum && var.defaultValue != null) {
|
||||
enumDefault = var.defaultValue;
|
||||
}
|
||||
super.updateCodegenPropertyEnum(var);
|
||||
if (var.isEnum && enumDefault != null) {
|
||||
var.defaultValue = enumDefault;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDefaultValue(Schema p) {
|
||||
p = ModelUtils.getReferencedSchema(this.openAPI, p);
|
||||
if (ModelUtils.isStringSchema(p)) {
|
||||
if (p.getDefault() != null) {
|
||||
return "\"" + escapeText((String) p.getDefault()) + "\"";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return super.toDefaultValue(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CodegenProperty fromProperty(String name, Schema p) {
|
||||
CodegenProperty prop = super.fromProperty(name, p);
|
||||
String cc = camelize(prop.name, true);
|
||||
if (isReservedWord(cc)) {
|
||||
cc = escapeReservedWord(cc);
|
||||
}
|
||||
prop.nameInCamelCase = cc;
|
||||
return prop;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
|
||||
// The superclass determines the list of required golang imports. The actual list of imports
|
||||
// depends on which types are used, some of which are changed in the code below (but then preserved
|
||||
// and used through x-go-base-type in templates). So super.postProcessModels
|
||||
// must be invoked at the beginning of this method.
|
||||
objs = super.postProcessModels(objs);
|
||||
|
||||
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
|
||||
|
||||
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
|
||||
for (Map<String, Object> m : models) {
|
||||
Object v = m.get("model");
|
||||
if (v instanceof CodegenModel) {
|
||||
CodegenModel model = (CodegenModel) v;
|
||||
if (model.isEnum) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (CodegenProperty param : model.vars) {
|
||||
param.vendorExtensions.put("x-go-base-type", param.dataType);
|
||||
if (!param.isNullable || param.isMapContainer || param.isListContainer ||
|
||||
param.isFreeFormObject || param.isAnyType) {
|
||||
continue;
|
||||
}
|
||||
if (param.isDateTime) {
|
||||
// Note this could have been done by adding the following line in processOpts(),
|
||||
// however, we only want to represent the DateTime object as NullableTime if
|
||||
// it's marked as nullable in the spec.
|
||||
// typeMapping.put("DateTime", "NullableTime");
|
||||
param.dataType = "NullableTime";
|
||||
} else {
|
||||
param.dataType = "Nullable" + Character.toUpperCase(param.dataType.charAt(0))
|
||||
+ param.dataType.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
// additional import for different cases
|
||||
// oneOf
|
||||
if (model.oneOf != null && !model.oneOf.isEmpty()) {
|
||||
imports.add(createMapping("import", "fmt"));
|
||||
}
|
||||
|
||||
// anyOf
|
||||
if (model.anyOf != null && !model.anyOf.isEmpty()) {
|
||||
imports.add(createMapping("import", "fmt"));
|
||||
}
|
||||
|
||||
// additionalProperties: true and parent
|
||||
if (model.isAdditionalPropertiesTrue && model.parent != null && Boolean.FALSE.equals(model.isMapModel)) {
|
||||
imports.add(createMapping("import", "reflect"));
|
||||
imports.add(createMapping("import", "strings"));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return objs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
|
||||
objs = super.postProcessOperationsWithModels(objs, allModels);
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
HashMap<String, CodegenModel> modelMaps = new HashMap<String, CodegenModel>();
|
||||
HashMap<String, Integer> processedModelMaps = new HashMap<String, Integer>();
|
||||
|
||||
for (Object o : allModels) {
|
||||
HashMap<String, Object> h = (HashMap<String, Object>) o;
|
||||
CodegenModel m = (CodegenModel) h.get("model");
|
||||
modelMaps.put(m.classname, m);
|
||||
}
|
||||
|
||||
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
|
||||
for (CodegenOperation op : operationList) {
|
||||
for (CodegenParameter p : op.allParams) {
|
||||
p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps));
|
||||
}
|
||||
}
|
||||
|
||||
processedModelMaps.clear();
|
||||
for (CodegenOperation operation : operationList) {
|
||||
for (CodegenParameter cp : operation.allParams) {
|
||||
cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps));
|
||||
}
|
||||
}
|
||||
|
||||
return objs;
|
||||
}
|
||||
|
||||
private String constructExampleCode(CodegenParameter codegenParameter, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
|
||||
if (codegenParameter.isListContainer) { // array
|
||||
return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
|
||||
} else if (codegenParameter.isMapContainer) {
|
||||
return "map[string]string{ \"Key\" = \"Value\" }";
|
||||
} else if (codegenParameter.isPrimitiveType) { // primitive type
|
||||
if (codegenParameter.isString) {
|
||||
if (StringUtils.isEmpty(codegenParameter.example)) {
|
||||
return "\"" + codegenParameter.example + "\"";
|
||||
} else {
|
||||
return "\"" + codegenParameter.paramName + "_example\"";
|
||||
}
|
||||
} else if (codegenParameter.isBoolean) { // boolean
|
||||
if (Boolean.parseBoolean(codegenParameter.example)) {
|
||||
return "true";
|
||||
} else {
|
||||
return "false";
|
||||
}
|
||||
} else if (codegenParameter.isUri) { // URL
|
||||
return "URL(string: \"https://example.com\")!";
|
||||
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
|
||||
return "Get-Date";
|
||||
} else { // numeric
|
||||
if (StringUtils.isEmpty(codegenParameter.example)) {
|
||||
return codegenParameter.example;
|
||||
} else {
|
||||
return "987";
|
||||
}
|
||||
}
|
||||
} else { // model
|
||||
// look up the model
|
||||
if (modelMaps.containsKey(codegenParameter.dataType)) {
|
||||
return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap);
|
||||
} else {
|
||||
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType);
|
||||
return "TODO";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String constructExampleCode(CodegenProperty codegenProperty, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
|
||||
if (codegenProperty.isListContainer) { // array
|
||||
return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")";
|
||||
} else if (codegenProperty.isMapContainer) { // map
|
||||
return "map[string]string{ \"Key\" = \"Value\" }";
|
||||
} else if (codegenProperty.isPrimitiveType) { // primitive type
|
||||
if (codegenProperty.isString) {
|
||||
if (StringUtils.isEmpty(codegenProperty.example)) {
|
||||
return "\"" + codegenProperty.example + "\"";
|
||||
} else {
|
||||
return "\"" + codegenProperty.name + "_example\"";
|
||||
}
|
||||
} else if (codegenProperty.isBoolean) { // boolean
|
||||
if (Boolean.parseBoolean(codegenProperty.example)) {
|
||||
return "true";
|
||||
} else {
|
||||
return "false";
|
||||
}
|
||||
} else if (codegenProperty.isUri) { // URL
|
||||
return "\"https://example.com\")!";
|
||||
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
|
||||
return "time.Now()";
|
||||
} else { // numeric
|
||||
String example;
|
||||
if (StringUtils.isEmpty(codegenProperty.example)) {
|
||||
example = codegenProperty.example;
|
||||
} else {
|
||||
example = "123";
|
||||
}
|
||||
|
||||
if (codegenProperty.isLong) {
|
||||
return "int64(" + example + ")";
|
||||
} else {
|
||||
return example;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// look up the model
|
||||
if (modelMaps.containsKey(codegenProperty.dataType)) {
|
||||
return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap);
|
||||
} else {
|
||||
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType);
|
||||
return "\"TODO\"";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String constructExampleCode(CodegenModel codegenModel, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
|
||||
String example;
|
||||
|
||||
// break infinite recursion. Return, in case a model is already processed in the current context.
|
||||
String model = codegenModel.name;
|
||||
if (processedModelMap.containsKey(model)) {
|
||||
int count = processedModelMap.get(model);
|
||||
if (count == 1) {
|
||||
processedModelMap.put(model, 2);
|
||||
} else if (count == 2) {
|
||||
return "";
|
||||
} else {
|
||||
throw new RuntimeException("Invalid count when constructing example: " + count);
|
||||
}
|
||||
} else {
|
||||
processedModelMap.put(model, 1);
|
||||
}
|
||||
|
||||
example = "" + goImportAlias + "." + codegenModel.name + "{";
|
||||
List<String> propertyExamples = new ArrayList<>();
|
||||
for (CodegenProperty codegenProperty : codegenModel.allVars) {
|
||||
propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap));
|
||||
}
|
||||
example += StringUtils.join(propertyExamples, ", ");
|
||||
example += "}";
|
||||
return example;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
/*
|
||||
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
|
||||
* Copyright 2018 SmartBear Software
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.openapitools.codegen.languages;
|
||||
|
||||
import org.openapitools.codegen.CliOption;
|
||||
import org.openapitools.codegen.CodegenConstants;
|
||||
import org.openapitools.codegen.CodegenType;
|
||||
import org.openapitools.codegen.SupportingFile;
|
||||
import org.openapitools.codegen.meta.features.*;
|
||||
import org.openapitools.codegen.meta.GeneratorMetadata;
|
||||
import org.openapitools.codegen.meta.Stability;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.EnumSet;
|
||||
|
||||
public class GoDeprecatedClientCodegen extends AbstractGoCodegen {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(GoDeprecatedClientCodegen.class);
|
||||
|
||||
protected String packageVersion = "1.0.0";
|
||||
protected String apiDocPath = "docs/";
|
||||
protected String modelDocPath = "docs/";
|
||||
protected boolean isGoSubmodule = false;
|
||||
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
|
||||
public static final String WITH_XML = "withXml";
|
||||
public static final String STRUCT_PREFIX = "structPrefix";
|
||||
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
|
||||
public static final String GENERATE_INTERFACES = "generateInterfaces";
|
||||
|
||||
public GoDeprecatedClientCodegen() {
|
||||
super();
|
||||
|
||||
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.DEPRECATED).build();
|
||||
|
||||
modifyFeatureSet(features -> features
|
||||
.includeDocumentationFeatures(DocumentationFeature.Readme)
|
||||
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML))
|
||||
.securityFeatures(EnumSet.of(
|
||||
SecurityFeature.BasicAuth,
|
||||
SecurityFeature.ApiKey,
|
||||
SecurityFeature.OAuth2_Implicit
|
||||
))
|
||||
.includeGlobalFeatures(
|
||||
GlobalFeature.ParameterizedServer
|
||||
)
|
||||
.excludeGlobalFeatures(
|
||||
GlobalFeature.XMLStructureDefinitions,
|
||||
GlobalFeature.Callbacks,
|
||||
GlobalFeature.LinkObjects,
|
||||
GlobalFeature.ParameterStyling
|
||||
)
|
||||
.excludeSchemaSupportFeatures(
|
||||
SchemaSupportFeature.Polymorphism
|
||||
)
|
||||
.includeParameterFeatures(
|
||||
ParameterFeature.Cookie
|
||||
)
|
||||
.includeClientModificationFeatures(
|
||||
ClientModificationFeature.BasePath,
|
||||
ClientModificationFeature.UserAgent
|
||||
)
|
||||
);
|
||||
|
||||
outputFolder = "generated-code/go-deprecated";
|
||||
modelTemplateFiles.put("model.mustache", ".go");
|
||||
apiTemplateFiles.put("api.mustache", ".go");
|
||||
|
||||
modelDocTemplateFiles.put("model_doc.mustache", ".md");
|
||||
apiDocTemplateFiles.put("api_doc.mustache", ".md");
|
||||
|
||||
embeddedTemplateDir = templateDir = "go-deprecated";
|
||||
|
||||
// default HIDE_GENERATION_TIMESTAMP to true
|
||||
hideGenerationTimestamp = Boolean.TRUE;
|
||||
|
||||
cliOptions.add(CliOption.newBoolean(CodegenConstants.IS_GO_SUBMODULE, CodegenConstants.IS_GO_SUBMODULE_DESC));
|
||||
cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs"));
|
||||
cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)"));
|
||||
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
|
||||
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
|
||||
cliOptions.add(CliOption.newBoolean(WITH_AWSV4_SIGNATURE, "whether to include AWS v4 signature support"));
|
||||
cliOptions.add(CliOption.newBoolean(GENERATE_INTERFACES, "Generate interfaces for api classes"));
|
||||
|
||||
// option to change the order of form/body parameter
|
||||
cliOptions.add(CliOption.newBoolean(
|
||||
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS,
|
||||
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC)
|
||||
.defaultValue(Boolean.FALSE.toString()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
|
||||
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
|
||||
} else {
|
||||
setPackageName("openapi");
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
|
||||
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
|
||||
} else {
|
||||
setPackageVersion("1.0.0");
|
||||
}
|
||||
|
||||
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
|
||||
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
|
||||
|
||||
additionalProperties.put("apiDocPath", apiDocPath);
|
||||
additionalProperties.put("modelDocPath", modelDocPath);
|
||||
|
||||
modelPackage = packageName;
|
||||
apiPackage = packageName;
|
||||
|
||||
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
|
||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
|
||||
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
|
||||
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
|
||||
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
|
||||
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
|
||||
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
|
||||
|
||||
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
|
||||
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
|
||||
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(WITH_AWSV4_SIGNATURE)) {
|
||||
setWithAWSV4Signature(Boolean.parseBoolean(additionalProperties.get(WITH_AWSV4_SIGNATURE).toString()));
|
||||
additionalProperties.put(WITH_AWSV4_SIGNATURE, withAWSV4Signature);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(WITH_XML)) {
|
||||
setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString()));
|
||||
additionalProperties.put(WITH_XML, withXml);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
|
||||
setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
|
||||
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, enumClassPrefix);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.IS_GO_SUBMODULE)) {
|
||||
setIsGoSubmodule(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.IS_GO_SUBMODULE).toString()));
|
||||
additionalProperties.put(CodegenConstants.IS_GO_SUBMODULE, isGoSubmodule);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(STRUCT_PREFIX)) {
|
||||
setStructPrefix(Boolean.parseBoolean(additionalProperties.get(STRUCT_PREFIX).toString()));
|
||||
additionalProperties.put(STRUCT_PREFIX, structPrefix);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(GENERATE_INTERFACES)) {
|
||||
setGenerateInterfaces(Boolean.parseBoolean(additionalProperties.get(GENERATE_INTERFACES).toString()));
|
||||
additionalProperties.put(GENERATE_INTERFACES, generateInterfaces);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see org.openapitools.codegen.CodegenType
|
||||
*/
|
||||
@Override
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the generator
|
||||
* to select the library with the -g flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "go-deprecated";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
@Override
|
||||
public String getHelp() {
|
||||
return "Generates a Go client library (beta). NOTE: this generator has been deprecated. Please use `go` client generator instead.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Location to write api files. You can use the apiPackage() as defined when the class is
|
||||
* instantiated
|
||||
*/
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + File.separator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + File.separator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiDocFileFolder() {
|
||||
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String modelDocFileFolder() {
|
||||
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelDocFilename(String name) {
|
||||
return toModelName(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiDocFilename(String name) {
|
||||
return toApiName(name);
|
||||
}
|
||||
|
||||
public void setPackageVersion(String packageVersion) {
|
||||
this.packageVersion = packageVersion;
|
||||
}
|
||||
|
||||
public void setIsGoSubmodule(boolean isGoSubmodule) {
|
||||
this.isGoSubmodule = isGoSubmodule;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -136,6 +136,8 @@ public class GoServerCodegen extends AbstractGoCodegen {
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
|
||||
/*
|
||||
* Additional Properties. These values can be passed to the templates and
|
||||
* are available in models, apis, and supporting files
|
||||
@@ -199,8 +201,6 @@ public class GoServerCodegen extends AbstractGoCodegen {
|
||||
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
|
||||
supportingFiles.add(new SupportingFile("routers.mustache", sourceFolder, "routers.go"));
|
||||
supportingFiles.add(new SupportingFile("logger.mustache", sourceFolder, "logger.go"));
|
||||
supportingFiles.add(new SupportingFile("impl.mustache",sourceFolder, "impl.go"));
|
||||
supportingFiles.add(new SupportingFile("helpers.mustache", sourceFolder, "helpers.go"));
|
||||
supportingFiles.add(new SupportingFile("api.mustache", sourceFolder, "api.go"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")
|
||||
.doNotOverwrite());
|
||||
|
||||
@@ -1368,20 +1368,12 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
|
||||
}
|
||||
if (this.generateSpringApplication) {
|
||||
if (supportMultipleSpringServices) {
|
||||
SupportingFile supportingFile = null;
|
||||
for (SupportingFile sf : supportingFiles) {
|
||||
if ("server/ApplicationContext.xml.mustache".equals(sf.getTemplateFile())) {
|
||||
supportingFile = sf;
|
||||
if ("server/ApplicationContext.xml.mustache".equals(sf.templateFile)) {
|
||||
sf.destinationFilename = "ApplicationContext-" + invokerPackage + ".xml";
|
||||
break;
|
||||
}
|
||||
}
|
||||
supportingFiles.remove(supportingFile);
|
||||
SupportingFile updated = new SupportingFile(
|
||||
supportingFile.getTemplateFile(),
|
||||
supportingFile.getFolder(),
|
||||
"ApplicationContext-" + invokerPackage + ".xml"
|
||||
);
|
||||
supportingFiles.add(updated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +72,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
|
||||
super();
|
||||
|
||||
supportsInheritance = true;
|
||||
useTags = true;
|
||||
|
||||
artifactId = "openapi-cxf-server";
|
||||
|
||||
@@ -80,7 +79,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
|
||||
|
||||
// clioOptions default redifinition need to be updated
|
||||
updateOption(CodegenConstants.ARTIFACT_ID, this.getArtifactId());
|
||||
updateOption(USE_TAGS, String.valueOf(true));
|
||||
|
||||
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
|
||||
|
||||
@@ -236,6 +234,12 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
|
||||
return "jaxrs-cxf";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
|
||||
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
|
||||
co.subresourceOperation = !co.path.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
|
||||
super.postProcessModelProperty(model, property);
|
||||
|
||||
@@ -325,16 +325,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
supportingFiles.add(new SupportingFile("ServerVariable.mustache", invokerFolder, "ServerVariable.java"));
|
||||
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
|
||||
|
||||
if (dateLibrary.equals("java8") && (isLibrary(WEBCLIENT) || isLibrary(VERTX) || isLibrary(RESTTEMPLATE) || isLibrary(RESTEASY) || isLibrary(MICROPROFILE) || isLibrary(JERSEY2))) {
|
||||
supportingFiles.add(new SupportingFile("JavaTimeFormatter.mustache", invokerFolder, "JavaTimeFormatter.java"));
|
||||
}
|
||||
|
||||
if (!(RESTTEMPLATE.equals(getLibrary()) || isLibrary(REST_ASSURED) || isLibrary(NATIVE) || isLibrary(MICROPROFILE))) {
|
||||
if (!(RESTTEMPLATE.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) {
|
||||
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
|
||||
}
|
||||
|
||||
// google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer)
|
||||
if (!(isLibrary(GOOGLE_API_CLIENT) || isLibrary(REST_ASSURED) || isLibrary(NATIVE) || isLibrary(MICROPROFILE))) {
|
||||
if (!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) {
|
||||
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
|
||||
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.mustache", authFolder, "HttpBearerAuth.java"));
|
||||
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
|
||||
@@ -481,7 +478,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
Iterator<SupportingFile> iter = supportingFiles.iterator();
|
||||
while (iter.hasNext()) {
|
||||
SupportingFile sf = iter.next();
|
||||
if (sf.getTemplateFile().startsWith("auth/")) {
|
||||
if (sf.templateFile.startsWith("auth/")) {
|
||||
iter.remove();
|
||||
}
|
||||
}
|
||||
@@ -782,14 +779,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
Map<String, Object> mo = (Map<String, Object>) _mo;
|
||||
CodegenModel cm = (CodegenModel) mo.get("model");
|
||||
boolean addImports = false;
|
||||
|
||||
for (CodegenProperty var : cm.vars) {
|
||||
if (this.openApiNullable) {
|
||||
boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable);
|
||||
// only add JsonNullable and related imports to optional and nullable values
|
||||
addImports |= isOptionalNullable;
|
||||
var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable);
|
||||
}
|
||||
boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable);
|
||||
// only add JsonNullable and related imports to optional and nullable values
|
||||
addImports |= isOptionalNullable;
|
||||
var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable);
|
||||
|
||||
if (Boolean.TRUE.equals(var.getVendorExtensions().get("x-enum-as-string"))) {
|
||||
// treat enum string as just string
|
||||
@@ -814,7 +808,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
importsHashSet.put("import", "java.util.HashSet");
|
||||
imports.add(importsHashSet);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (addImports) {
|
||||
@@ -831,35 +824,35 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// add implements for serializable/parcelable to all models
|
||||
for (Object _mo : models) {
|
||||
Map<String, Object> mo = (Map<String, Object>) _mo;
|
||||
CodegenModel cm = (CodegenModel) mo.get("model");
|
||||
// add implements for serializable/parcelable to all models
|
||||
for (Object _mo : models) {
|
||||
Map<String, Object> mo = (Map<String, Object>) _mo;
|
||||
CodegenModel cm = (CodegenModel) mo.get("model");
|
||||
|
||||
cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());
|
||||
if (JERSEY2.equals(getLibrary())) {
|
||||
cm.getVendorExtensions().put("x-implements", new ArrayList<String>());
|
||||
cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());
|
||||
if (JERSEY2.equals(getLibrary())) {
|
||||
cm.getVendorExtensions().put("x-implements", new ArrayList<String>());
|
||||
|
||||
if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) {
|
||||
// if oneOf contains "null" type
|
||||
cm.isNullable = true;
|
||||
cm.oneOf.remove("ModelNull");
|
||||
}
|
||||
|
||||
if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) {
|
||||
// if anyOf contains "null" type
|
||||
cm.isNullable = true;
|
||||
cm.anyOf.remove("ModelNull");
|
||||
}
|
||||
if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) {
|
||||
// if oneOf contains "null" type
|
||||
cm.isNullable = true;
|
||||
cm.oneOf.remove("ModelNull");
|
||||
}
|
||||
if (this.parcelableModel) {
|
||||
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Parcelable");
|
||||
}
|
||||
if (this.serializableModel) {
|
||||
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Serializable");
|
||||
|
||||
if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) {
|
||||
// if anyOf contains "null" type
|
||||
cm.isNullable = true;
|
||||
cm.anyOf.remove("ModelNull");
|
||||
}
|
||||
}
|
||||
if (this.parcelableModel) {
|
||||
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Parcelable");
|
||||
}
|
||||
if (this.serializableModel) {
|
||||
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Serializable");
|
||||
}
|
||||
}
|
||||
|
||||
return objs;
|
||||
@@ -958,6 +951,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
setSerializationLibrary(serializationLibrary);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
|
||||
generateYAMLSpecFile(objs);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user