Compare commits

..

58 Commits

Author SHA1 Message Date
Bodo Graumann
f3f5fef279 Typescript refactor: Platform select for browser and node (#4500)
* Use string form of filename parameter

This works for the form-data library and is also compatible with the
browser FormData object.

* Add new option to select platform node or browser

When no platform is selected, a default is chosen by the framework
option and likewise the file data type option is implied by the
platform.

* Remove redundant import of node dns module

* Only use form-data library for node platform

* Generate npm package from npmName option

* Use method convertPropertyToBooleanAndWriteBack

* Generate typescript samples with ensure-up-to-date
2020-01-18 06:31:27 -05:00
Bodo Graumann
6dfe637b21 Typescript refactor: stub rxjs (#4424)
* Remove unused supportsES6 field from codegen

* Add a new switch for RXJS

* Remove redundant npm dependency on rxjs4 types

* Fix return type of PromiseMiddleware methods

* Install webpack dependency to run jquery tests

* Update form-data to 2.5 which includes typings

* Add missing dependency on node typings

* Fix test artifact name typo

* Stub rxjs when it is not explicitly enabled
2019-11-19 11:48:08 -05:00
Bodo Graumann
a738e95aee Refactor typescript merge master (#4319)
Merge master into ts-refactor
2019-11-01 11:04:18 -04:00
Tino Fuhrmann
9d08f8bc5b Updated typescript docs 2019-05-06 12:07:03 +02:00
Tino Fuhrmann
9e49c7e942 Fixed missing fetch definition in TS default tests 2019-05-06 12:03:07 +02:00
Tino Fuhrmann
bc734da7d4 Ensured up to date 2019-05-05 22:58:45 +02:00
Tino Fuhrmann
abff890b90 Fixed a couple issues with pom.xml 2019-05-05 22:39:52 +02:00
Tino Fuhrmann
b796270880 Removed tabs in TypeScriptClientCodegen 2019-05-05 20:43:50 +02:00
Tino Fuhrmann
02c1d9ff64 Added pom.xmls, fixed packagejsons and hopefully webppack 2019-05-05 20:32:01 +02:00
Tino Fuhrmann
7d69d0b9cb Added jquery library 2019-05-05 16:44:32 +02:00
Tino Fuhrmann
3e94fd15cc Added gitignore and git_push 2019-05-03 20:22:29 +02:00
Tino Fuhrmann
491fae4c25 Updated docs 2019-05-02 15:10:13 +02:00
Tino Fuhrmann
be3e24b681 Added typescript to docs/generators 2019-05-01 11:26:25 +02:00
Tino Fuhrmann
7d0b3e1879 Fixed compilation issues in TypeScriptClientCodegen 2019-05-01 10:50:57 +02:00
Tino Fuhrmann
8b138ecd81 Reverted changes to README to master 2019-05-01 10:45:51 +02:00
Tino Fuhrmann
496c0c8bdc Removed accidentally created generated code 2019-05-01 10:45:07 +02:00
Tino Fuhrmann
b8e31fcddd Ignore openapi-generator-cli/bin 2019-05-01 10:43:47 +02:00
Tino Fuhrmann
64b8505010 Added comments 2019-04-30 23:25:24 +02:00
Tino Fuhrmann
5f163da848 Added comments & license info 2019-04-30 23:25:24 +02:00
Tino Fuhrmann
7f5615485d Fixed date-time and date handling 2019-04-30 23:25:24 +02:00
Tino Fuhrmann
e700a08a8f Set discriminator value automatically 2019-04-30 23:20:50 +02:00
Tino Fuhrmann
74bb8ccfe7 Configure discriminator correctly 2019-04-30 23:20:50 +02:00
Tino Fuhrmann
01b0ff6008 Made discriminator and attributeTypeMap readonly 2019-04-30 23:20:50 +02:00
Tino Fuhrmann
5323a5d7a6 Added promise based middleware 2019-04-30 23:20:50 +02:00
Tino Fuhrmann
8c03ea8ca5 Use observables internally 2019-04-30 23:20:50 +02:00
Tino Fuhrmann
c90c3f9d7b Restructured module layout 2019-04-30 23:20:50 +02:00
Tino Fuhrmann
9c17bc5721 Remove tab 2019-04-30 23:20:50 +02:00
Tino Fuhrmann
a0e3f18f2f Use string union for enums 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
647474f3d9 Made api call configuration separately settable 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
4720467cbb Fixed file uploads 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
2468b748d3 Additional tests for pet store api 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
9a9e62cfa5 Removed tabs in DefaultCodegen 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
5174e7539b Removed tabs in TypeScriptClientCodegen 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
fe0cb07afb Added handling for different http status codes and test for deletePet 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
878ea6e1c1 Fixed ObjectSerializer test 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
69dfdd57a6 Added simple test for PetApi 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
502e209bfe [TS-Refactor] Added tests for Object Serializer 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
8d29ca42d5 Added server variable configuration to ts-refactor 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
49219fa48a Added ts client codegen to root pom.xml and travis 2019-04-30 23:20:49 +02:00
Tino Fuhrmann
f4b3eb011b Removed tabs from TypeScriptClientCodegen 2019-04-30 23:19:34 +02:00
Tino Fuhrmann
ef065f3013 Added pom.xml files to TypeScript PetStore client samples 2019-04-30 23:19:34 +02:00
Tino Fuhrmann
29940ef0b1 Removed TODOs 2019-04-30 23:19:34 +02:00
Tino Fuhrmann
dd7d8c0271 Reverted: http library.send returns string again 2019-04-30 23:19:34 +02:00
Tino Fuhrmann
0da5238e24 Restructured TypeScript generator 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
2e8446ceee Added middleware to fetch 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
662242157f Ignore dist folder in typescript client sample 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
5adefaf53f Implemented fetch client 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
8dca5e4cbe Implemented RequestFactory and Processor completely 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
e21a48dd64 WIP: api modeling 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
894bddac1b Updated auth 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
fe2cc24f4d WIP: Models & API 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
b0f8dc9505 Added sample for typescript client 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
8f82cdec7d Added servers 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
64f29483ce Added auth module 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
94432cff92 Added model generation with imports 2019-04-30 23:19:33 +02:00
Tino Fuhrmann
3e745b71f2 Modified http lib, added config & middleware definition to ts-fetch 2019-04-30 23:19:32 +02:00
Tino Fuhrmann
f90e1b59f5 Added generic enum 2019-04-30 23:19:32 +02:00
Tino Fuhrmann
dd6835393d Added http module draft 2019-04-30 23:19:32 +02:00
1936 changed files with 22546 additions and 20894 deletions

View File

@@ -6,5 +6,5 @@
- [ ] Read the [contribution guidelines](https://github.com/openapitools/openapi-generator/blob/master/CONTRIBUTING.md).
- [ ] If contributing template-only or documentation-only changes which will change sample output, [build the project](https://github.com/OpenAPITools/openapi-generator#14---build-projects) before.
- [ ] Run the shell script(s) under `./bin/` (or Windows batch scripts under`.\bin\windows`) to update Petstore samples related to your fix. This is important, as CI jobs will verify _all_ generator outputs of your HEAD commit, and these must match the expectations made by your contribution. You only need to run `./bin/{LANG}-petstore.sh`, `./bin/openapi3/{LANG}-petstore.sh` if updating the code or mustache templates for a language (`{LANG}`) (e.g. php, ruby, python, etc).
- [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `4.3.x`, `5.0.x`. Default: `master`.
- [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `4.1.x`, `5.0.x`. Default: `master`.
- [ ] Copy the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) to review the pull request if your PR is targeting a particular programming language.

1
.gitignore vendored
View File

@@ -7,6 +7,7 @@ out/
classpath.txt
version.properties
modules/openapi-generator-gradle-plugin/bin/
modules/openapi-generator-cli/bin/
!modules/openapi-generator-cli/src/main/resources/version.properties
.project
.classpath

View File

@@ -20,6 +20,7 @@ cache:
- $HOME/samples/client/petstore/php/OpenAPIToolsClient-php/vendor
- $HOME/samples/client/petstore/ruby/vendor/bundle
- $HOME/samples/client/petstore/python/.venv/
- $HOME/samples/client/petstore/typescript/tests/default/node_modules
- $HOME/samples/client/petstore/typescript-node/npm/node_modules
- $HOME/samples/client/petstore/typescript-node/npm/typings/
- $HOME/samples/client/petstore/typescript-fetch/tests/default/node_modules
@@ -138,7 +139,6 @@ script:
# test maven plugin
- mvn clean compile -f modules/openapi-generator-maven-plugin/examples/java-client.xml
- mvn clean compile -f modules/openapi-generator-maven-plugin/examples/multi-module/pom.xml
- mvn clean compile -f modules/openapi-generator-maven-plugin/examples/kotlin.xml
# test gradle plugin
- (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk)
- (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate)

View File

@@ -28,7 +28,7 @@ elif [ "$NODE_INDEX" = "2" ]; then
git checkout -- .
# look for outdated samples
./bin/utils/ensure-up-to-date --batch
./bin/utils/ensure-up-to-date
fi
#elif [ "$NODE_INDEX" = "3" ]; then
echo "Running node $NODE_INDEX to test haskell"

View File

@@ -128,6 +128,8 @@ public class PetApiTest {
//empty
}
});
// the API call should be executed asynchronously, so result should be empty at the moment
assertTrue(result.isEmpty());
// wait for the asynchronous call to finish (at most 10 seconds)
final int maxTry = 10;
@@ -144,14 +146,6 @@ public class PetApiTest {
}
} while (result.isEmpty());
assertPetMatches(pet, fetched);
}
@Test
public void testCreateAndGetPetAsyncInvalidID() throws Exception {
Pet pet = createPet();
api.addPet(pet);
// to store returned Pet or error message/exception
final Map<String, Object> result = new HashMap<String, Object>();
// test getting a nonexistent pet
result.clear();
@@ -178,11 +172,8 @@ public class PetApiTest {
});
// wait for the asynchronous call to finish (at most 10 seconds)
final int maxTry = 10;
int tryCount = 1;
Pet fetched = null;
tryCount = 1;
ApiException exception = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
@@ -423,16 +414,16 @@ public class PetApiTest {
assertEquals(expected.getId(), actual.getId());
assertNotNull(actual.getCategory());
assertEquals(expected.getCategory().getName(),
actual.getCategory().getName());
actual.getCategory().getName());
}
/**
* Assert that the given upload/download progress list satisfies the
* following constraints:
* <p>
* - List is not empty
* - Byte count should be nondecreasing
* - The last element, and only the last element, should have done=true
*
* - List is not empty
* - Byte count should be nondecreasing
* - The last element, and only the last element, should have done=true
*/
private void assertValidProgress(List<Progress> progressList) {
assertFalse(progressList.isEmpty());
@@ -443,7 +434,7 @@ public class PetApiTest {
if (prev != null) {
if (prev.done || prev.bytes > progress.bytes) {
fail("Progress list out of order at index " + index
+ ": " + progressList);
+ ": " + progressList);
}
}
prev = progress;
@@ -459,9 +450,9 @@ public class PetApiTest {
private final CountDownLatch latch;
private final ConcurrentLinkedQueue<Progress> uploadProgress =
new ConcurrentLinkedQueue<Progress>();
new ConcurrentLinkedQueue<Progress>();
private final ConcurrentLinkedQueue<Progress> downloadProgress =
new ConcurrentLinkedQueue<Progress>();
new ConcurrentLinkedQueue<Progress>();
private boolean done;
private boolean success;

View File

@@ -2,18 +2,12 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.2.1`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.2.0-SNAPSHOT`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/master)](https://cloud.drone.io/OpenAPITools/openapi-generator)
[`4.3.x`](https://github.com/OpenAPITools/openapi-generator/tree/4.3.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/4.3.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/4.3.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=4.3.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=4.3.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/4.3.x)](https://cloud.drone.io/OpenAPITools/openapi-generator)
[`5.0.x`](https://github.com/OpenAPITools/openapi-generator/tree/5.0.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=5.0.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
@@ -108,9 +102,8 @@ 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/)| 13.05.2020 | Major release with breaking changes (no fallback)
4.3.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.3.0-SNAPSHOT/)| 29.02.2020 | Minor release (breaking changes with fallbacks)
4.2.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.2.1/)| 15.11.2019 | Patch release
[4.2.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.2.0) (latest stable release) | 31.10.2019 | Minor release (bug fixes, enhancements, breaking chanages with fallbacks)
4.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.2.0-SNAPSHOT/)| 09.10.2019 | Minor release (breaking changes with fallbacks)
[4.1.3](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.1.3) (latest stable release) | 04.10.2019 | Patch release (bug fixes, enhancements)
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
@@ -166,16 +159,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: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar`
JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.jar`
For **Mac/Linux** users:
```sh
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar -O openapi-generator-cli.jar
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.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 http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@@ -390,10 +383,10 @@ openapi-generator version
```
<!-- RELEASE_VERSION -->
Or install a particular OpenAPI Generator version (e.g. v4.2.0):
Or install a particular OpenAPI Generator version (e.g. v4.1.3):
```sh
npm install @openapitools/openapi-generator-cli@cli-4.2.0 -g
npm install @openapitools/openapi-generator-cli@cli-4.1.3 -g
```
Or install it as dev-dependency:
@@ -417,7 +410,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](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar)
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.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`
@@ -522,7 +515,7 @@ Please refer to [customization.md](docs/customization.md) on how to customize th
### [3.2 - Workflow Integration (Maven, Gradle, Github, CI/CD)](#table-of-contents)
Please refer to [integration.md](docs/integration.md) on how to integrate OpenAPI generator with Maven, Gradle, sbt, Bazel, Github and CI/CD.
Please refer to [integration.md](docs/integration.md) on how to integrate OpenAPI generator with Maven, Gradle, Github and CI/CD.
### [3.3 - Online OpenAPI generator](#table-of-contents)
@@ -584,7 +577,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Element AI](https://www.elementai.com/)
- [Fenergo](https://www.fenergo.com/)
- [FormAPI](https://formapi.io/)
- [FreshCells](https://www.freshcells.de/)
- [Fuse](https://www.fuse.no/)
- [Gantner](https://www.gantner.com)
- [GenFlow](https://github.com/RepreZen/GenFlow)
@@ -594,7 +586,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [IBM](https://www.ibm.com/)
- [JustStar](https://www.juststarinfo.com)
- [Klarna](https://www.klarna.com/)
- [Kronsoft Development](https://www.kronsoft.ro/home/)
- [Médiavision](https://www.mediavision.fr/)
- [Metaswitch](https://www.metaswitch.com/)
- [Myworkout](https://myworkout.com)
@@ -604,8 +595,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Ponicode](https://ponicode.dev/)
- [Pricefx](https://www.pricefx.com/)
- [Prometheus/Alertmanager](https://github.com/prometheus/alertmanager)
- [QEDIT](https://qed-it.com)
- [Qulix Systems](https://www.qulix.com)
- [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch)
- [RedHat](https://www.redhat.com)
- [RepreZen API Studio](https://www.reprezen.com/swagger-openapi-code-generation-api-first-microservices-enterprise-development)
@@ -688,9 +677,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2019-10-16 - [How to ship APIs faster?](https://medium.com/@accounts_76224/how-to-ship-apis-faster-cabef2f819e4) by [Simon Guilliams @ PoniCode](https://ponicode.dev)
- 2019-10-22 - [OpenAPI + Spring Boot(Kotlin)でファイルダウンロードAPIを作成する](https://qiita.com/boronngo/items/4b78b92526209daeaee9) by [Yuki Furukawa](https://twitter.com/yuki_furukawa5)
- 2019-10-24 - [Microprofile OpenAPI - Code First or Design First?](https://github.com/pe-st/apidocs/blob/master/MicroProfile-OpenAPI-all-slides.pdf) by [Peter [pɛʃə] Steiner](https://twitter.com/pesche) at [eclipsecon Europe 2019](https://www.eclipsecon.org/europe2019/sessions/microprofile-openapi-code-first-or-design-first)
- 2019-11-06 - [Generating API clients based on OpenAPI v3 specifications](https://98elements.com/blog/generating-api-clients-based-on-openapi-v3-specifications) by [Dominik Jastrzębski @ 98elements](https://98elements.com)
- 2019-11-06 - [OpenAPIを利用して自前のAPIサーバー(Sinatra)を移植した時のメモ](https://qiita.com/YasuhiroABE/items/c73920eab2d9d6e97fd9) by [Yasuhiro ABE](https://twitter.com/YasuhiroABE)
- 2019-11-11 - [TypeScript REST APIクライアント](https://qiita.com/unhurried/items/7b74f7d3c43545dadd2b) by [@unhurried](https://qiita.com/unhurried)
## [6 - About Us](#table-of-contents)
@@ -893,7 +879,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| Perl | @wing328 (2017/07) [:heart:](https://www.patreon.com/wing328) @yue9944882 (2019/06) |
| PHP | @jebentier (2017/07), @dkarlovi (2017/07), @mandrean (2017/08), @jfastnacht (2017/09), @ackintosh (2017/09) [:heart:](https://www.patreon.com/ackintosh/overview), @ybelenko (2018/07), @renepardon (2018/12) |
| PowerShell | |
| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @Jyhess (2019/01) @slash-arun (2019/11) |
| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @Jyhess (2019/01) |
| R | @Ramanth (2019/07) @saigiridhar21 (2019/07) |
| Ruby | @cliffano (2017/07) @zlx (2017/09) @autopp (2019/02) |
| Rust | @frol (2017/07) @farcaller (2017/08) @bjgill (2017/12) @richardwhiuk (2019/07) |

View File

@@ -1,6 +1,6 @@
{
"generatorName": "php-symfony",
"inputSpec": "modules/openapi-generator/src/test/resources/2_0/petstore.yaml",
"outputDir": "samples/server/petstore/php-symfony/SymfonyBundle-php",
"templateDir": "modules/openapi-generator/src/main/resources/php-symfony"
"inputSpec": "/Users/jim/projects/openapi-generator/bin/../modules/openapi-generator/src/test/resources/2_0/petstore.yaml",
"outputDir": "/Users/jim/projects/openapi-generator/bin/../samples/server/petstore/php-symfony/SymfonyBundle-php",
"templateDir": "/Users/jim/projects/openapi-generator/bin/../modules/openapi-generator/src/main/resources/php-symfony"
}

View File

@@ -27,11 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
args="generate -t modules/openapi-generator/src/main/resources/cpp-qt5-client \
-i modules/openapi-generator/src/test/resources/2_0/petstore.yaml \
-g cpp-qt5-client \
--additional-properties=cppNamespace=test_namespace \
--additional-properties=modelNamePrefix=PFX \
-o samples/client/petstore/cpp-qt5 $@"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-qt5-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-qt5-client -o samples/client/petstore/cpp-qt5 $@"
java $JAVA_OPTS -jar $executable $args
java $JAVA_OPTS -jar $executable $ags

View File

@@ -1,10 +1,8 @@
#!/bin/sh
./bin/kotlin-client-gson.sh
./bin/kotlin-client-nonpublic.sh
./bin/kotlin-client-okhttp3.sh
./bin/kotlin-client-petstore-multiplatform.sh
./bin/kotlin-client-petstore.sh
./bin/kotlin-client-string.sh
./bin/kotlin-client-threetenbp.sh
./bin/kotlin-client-nullable.sh

View File

@@ -1,32 +0,0 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
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 -B 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 -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-gson --additional-properties serializationLibrary=gson -o samples/client/petstore/kotlin-gson $@"
java ${JAVA_OPTS} -jar ${executable} ${ags}

View File

@@ -30,3 +30,5 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-nonpublic --additional-properties nonPublicApi=true -o samples/client/petstore/kotlin-nonpublic $@"
java ${JAVA_OPTS} -jar ${executable} ${ags}
cp CI/samples.ci/client/petstore/kotlin-string/pom.xml samples/client/petstore/kotlin-string/pom.xml

View File

@@ -1,32 +0,0 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
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 -B 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 -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-nullable --additional-properties nullableReturnType=true,serializableModel=true -o samples/client/petstore/kotlin-nullable $@"
java ${JAVA_OPTS} -jar ${executable} ${ags}

View File

@@ -30,3 +30,5 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-okhttp3 --library jvm-okhttp3 -o samples/client/petstore/kotlin-okhttp3 $@"
java ${JAVA_OPTS} -jar ${executable} ${ags}
#cp CI/samples.ci/client/petstore/kotlin-okhttp3/pom.xml samples/client/petstore/kotlin-okhttp3/pom.xml

View File

@@ -1,52 +0,0 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
if ! command -v gradle > /dev/null; then
echo "[WARN] This script requires a system gradle to be installed. Not treating this as an error."
exit 0
fi
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
./mvnw -B clean package
fi
\rm -rf "samples/meta-codegen-kotlin/lib"
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="meta -n myClientCodegen -t DOCUMENTATION -p com.my.company.codegen -o samples/meta-codegen-kotlin/lib -l kotlin $@"
java $JAVA_OPTS -jar $executable $ags
if [ ! -f samples/meta-codegen-kotlin/gradle/wrapper/gradle-wrapper.jar ]; then
(cd samples/meta-codegen-kotlin/ && gradle wrapper --gradle-version 5.6.2 --distribution-type bin)
fi
(cp samples/meta-codegen-kotlin/gradlew samples/meta-codegen-kotlin/lib/ && \
cp -R samples/meta-codegen-kotlin/gradle samples/meta-codegen-kotlin/lib/ && \
cd samples/meta-codegen-kotlin/lib && \
./gradlew shadowJar)
ags2="generate -g myClientCodegen -i modules/openapi-generator/src/test/resources/2_0/petstore.json -o samples/meta-codegen-kotlin/usage $@"
java $JAVA_OPTS -cp samples/meta-codegen-kotlin/lib/build/libs/my-client-codegen-openapi-generator-1.0-SNAPSHOT-all.jar:$executable org.openapitools.codegen.OpenAPIGenerator $ags2

View File

@@ -15,4 +15,3 @@
./bin/typescript-angular-v7-petstore-provided-in-root-with-npm.sh
./bin/typescript-angular-v8-petstore-provided-in-root-with-npm.sh
./bin/typescript-angular-v8-petstore-provided-in-root-with-prefixed-module-name.sh
./bin/typescript-angular-v8-petstore-single-request-parameter.sh

View File

@@ -26,7 +26,12 @@ then
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 typescript-angular -c bin/typescript-angular-v8-petstore-provided-in-root-with-npm.json -o samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter --additional-properties ngVersion=8.0.0,useSingleRequestParameter=true $@"
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
echo "Creating default (fetch) client!"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript -o samples/client/petstore/typescript/builds/default --additional-properties=platform=node,npmName=ts-petstore-client $@"
java $JAVA_OPTS -jar $executable $ags
echo "Creating jquery client!"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript -o samples/client/petstore/typescript/builds/jquery --additional-properties=framework=jquery,npmName=ts-petstore-client $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -1,20 +0,0 @@
## What is the purpose?
Running `./save_dart_keywords.sh` from this directory will generate `dart-keywords.txt` which contains the current Dart keywords and is used by the dart generator as a set of reserved words.
## When should the keywords be generated?
`save_dart_keywords.sh` should be run when a new version of Dart is release to update the keywords file.
The last Dart version that was used to generate the keywords can be found in `dart-version.txt`.
## What does the shellscript do?
1. compile a dart app
- `dart2native save-dart-keywords.dart`
1. run the dart app
- `./save-dart-keywords.exe`
1. the ouput is `dart-keywords.txt` and `dart-version.txt`

View File

@@ -1 +0,0 @@
Dart VM version: 2.7.0-dev.0.0 (Tue Nov 5 12:57:33 2019 +0100) on "macos_x64"

View File

@@ -1,194 +0,0 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.0"
analyzer:
dependency: "direct main"
description:
name: analyzer
url: "https://pub.dartlang.org"
source: hosted
version: "0.39.1"
args:
dependency: transitive
description:
name: args
url: "https://pub.dartlang.org"
source: hosted
version: "1.5.2"
async:
dependency: transitive
description:
name: async
url: "https://pub.dartlang.org"
source: hosted
version: "2.4.0"
charcode:
dependency: transitive
description:
name: charcode
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.2"
collection:
dependency: transitive
description:
name: collection
url: "https://pub.dartlang.org"
source: hosted
version: "1.14.12"
convert:
dependency: transitive
description:
name: convert
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.1"
crypto:
dependency: transitive
description:
name: crypto
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.3"
csslib:
dependency: transitive
description:
name: csslib
url: "https://pub.dartlang.org"
source: hosted
version: "0.16.1"
front_end:
dependency: transitive
description:
name: front_end
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.29"
glob:
dependency: transitive
description:
name: glob
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.0"
html:
dependency: transitive
description:
name: html
url: "https://pub.dartlang.org"
source: hosted
version: "0.14.0+3"
js:
dependency: transitive
description:
name: js
url: "https://pub.dartlang.org"
source: hosted
version: "0.6.1+1"
kernel:
dependency: transitive
description:
name: kernel
url: "https://pub.dartlang.org"
source: hosted
version: "0.3.29"
meta:
dependency: transitive
description:
name: meta
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.8"
node_interop:
dependency: transitive
description:
name: node_interop
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.3"
node_io:
dependency: transitive
description:
name: node_io
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.1+2"
package_config:
dependency: transitive
description:
name: package_config
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.0"
path:
dependency: transitive
description:
name: path
url: "https://pub.dartlang.org"
source: hosted
version: "1.6.4"
pedantic:
dependency: transitive
description:
name: pedantic
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.0+1"
pub_semver:
dependency: transitive
description:
name: pub_semver
url: "https://pub.dartlang.org"
source: hosted
version: "1.4.2"
source_span:
dependency: transitive
description:
name: source_span
url: "https://pub.dartlang.org"
source: hosted
version: "1.5.5"
string_scanner:
dependency: transitive
description:
name: string_scanner
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.5"
term_glyph:
dependency: transitive
description:
name: term_glyph
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.0"
typed_data:
dependency: transitive
description:
name: typed_data
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.6"
watcher:
dependency: transitive
description:
name: watcher
url: "https://pub.dartlang.org"
source: hosted
version: "0.9.7+12"
yaml:
dependency: transitive
description:
name: yaml
url: "https://pub.dartlang.org"
source: hosted
version: "2.2.0"
sdks:
dart: ">=2.6.0 <3.0.0"

View File

@@ -1,10 +0,0 @@
name: dart_keywords
description: Use the Dart SDK to generate Dart keywords.
version: 1.0.0+1
environment:
sdk: ">=2.6.0 <3.0.0"
dependencies:
analyzer:

View File

@@ -1,16 +0,0 @@
import 'dart:io';
import 'package:analyzer/dart/ast/token.dart';
main() {
// save keywords to a text file
final txtFile = File(
'../../../modules/openapi-generator/src/main/resources/dart/dart-keywords.txt');
String txtString = '';
for (String keyword in Keyword.keywords.keys.toList()) {
txtString += keyword + '\n';
}
txtString =
txtString.substring(0, txtString.length - 1); // remove last newline
txtFile.writeAsStringSync(txtString);
}

View File

@@ -1,3 +0,0 @@
dart2native save-dart-keywords.dart
./save-dart-keywords.exe
dart --version &> dart-version.txt

View File

@@ -1,22 +1,10 @@
#!/usr/bin/env bash
# this bash script runs the scripts for the 'mature' generators by default.
# Supports --batch option which will compile all generators defined under bin/ci/*.json
#!/bin/bash
# this bash script run the scripts for the 'mature' generators
# it ensures that all changes are committed into the 'samples/' folder
# shellcheck disable=SC2155
declare cwd="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
declare root="$(cd "$cwd" && cd ../../ && pwd)"
declare executable="${root}/modules/openapi-generator-cli/target/openapi-generator-cli.jar"
declare batch_mode="false"
echo "# START SCRIPT: $0"
echo "IMPORTANT: this script should be run by the CI (e.g. Shippable) to ensure that the 'samples/' folder is up to date."
if [ "--batch" = "$1" ]; then
batch_mode="true"
echo "Running in 'batch mode' (single JVM, mutliple threads)."
else
echo "When running locally execute with argument --batch."
fi
echo "Please press CTRL+C to stop or the script will continue in 5 seconds."
sleep 5
@@ -24,87 +12,83 @@ sleep 5
# LIST OF SCRIPTS:
declare -a scripts=(
# SAMPLES
"${root}/bin/ruby-client-petstore.sh"
"${root}/bin/ruby-client-petstore-faraday.sh"
"${root}/bin/openapi3/ruby-client-petstore.sh"
"${root}/bin/openapi3/ruby-client-faraday-petstore.sh"
"${root}/bin/java-petstore-all.sh"
"${root}/bin/java-jaxrs-petstore-server-all.sh"
"${root}/bin/java-msf4j-petstore-server.sh"
"${root}/bin/openapi3/jaxrs-jersey-petstore.sh"
"${root}/bin/spring-all-petstore.sh"
"${root}/bin/javascript-petstore-all.sh"
"${root}/bin/kotlin-client-all.sh"
"${root}/bin/kotlin-server-petstore.sh"
"${root}/bin/kotlin-springboot-petstore-server.sh"
"${root}/bin/kotlin-springboot-petstore-server-reactive.sh"
"${root}/bin/mysql-schema-petstore.sh"
"${root}/bin/nim-client-petstore.sh"
"${root}/bin/python-petstore-all.sh"
"${root}/bin/openapi3/python-petstore.sh"
"${root}/bin/php-petstore.sh"
"${root}/bin/php-silex-petstore-server.sh"
"${root}/bin/php-symfony-petstore.sh"
"${root}/bin/php-lumen-petstore-server.sh"
"${root}/bin/php-slim-server-petstore.sh"
"${root}/bin/php-slim4-server-petstore.sh"
"${root}/bin/php-ze-ph-petstore-server.sh"
"${root}/bin/openapi3/php-petstore.sh"
"${root}/bin/typescript-angularjs-petstore.sh"
"${root}/bin/typescript-angular-petstore-all.sh"
"${root}/bin/typescript-aurelia-petstore.sh"
"${root}/bin/typescript-axios-petstore-all.sh"
"${root}/bin/typescript-fetch-petstore-all.sh"
"${root}/bin/typescript-inversify-petstore.sh"
"${root}/bin/typescript-jquery-petstore-all.sh"
"${root}/bin/typescript-node-petstore-all.sh"
"${root}/bin/typescript-rxjs-petstore-all.sh"
"${root}/bin/rust-server-petstore.sh"
"${root}/bin/r-petstore.sh"
"${root}/bin/haskell-http-client-petstore.sh"
"${root}/bin/csharp-petstore.sh"
"${root}/bin/csharp-netcore-petstore-all.sh"
"${root}/bin/elixir-petstore.sh"
"${root}/bin/openapi3/go-petstore.sh"
"${root}/bin/go-experimental-petstore.sh"
"${root}/bin/go-petstore.sh"
"${root}/bin/go-petstore-withxml.sh"
"${root}/bin/go-petstore-server.sh"
"${root}/bin/go-gin-petstore-server.sh"
"${root}/bin/groovy-petstore.sh"
"${root}/bin/apex-petstore.sh"
"${root}/bin/perl-petstore-all.sh"
"${root}/bin/dart-jaguar-petstore.sh"
#"${root}/bin/dart-dio-petstore.sh"
"${root}/bin/dart-petstore.sh"
"${root}/bin/dart2-petstore.sh"
"${root}/bin/java-play-framework-petstore-server-all.sh"
#"${root}/bin/elm-petstore-all.sh"
"${root}/bin/meta-codegen.sh"
"./bin/ruby-client-petstore.sh"
"./bin/ruby-client-petstore-faraday.sh"
"./bin/openapi3/ruby-client-petstore.sh"
"./bin/openapi3/ruby-client-faraday-petstore.sh"
"./bin/java-petstore-all.sh"
"./bin/java-jaxrs-petstore-server-all.sh"
"./bin/java-msf4j-petstore-server.sh"
"./bin/openapi3/jaxrs-jersey-petstore.sh"
"./bin/spring-all-petstore.sh"
"./bin/javascript-petstore-all.sh"
"./bin/kotlin-client-petstore-multiplatform.sh"
"./bin/kotlin-client-petstore.sh"
"./bin/kotlin-client-string.sh"
"./bin/kotlin-client-threetenbp.sh"
"./bin/kotlin-server-petstore.sh"
"./bin/kotlin-springboot-petstore-server.sh"
"./bin/kotlin-springboot-petstore-server-reactive.sh"
"./bin/mysql-schema-petstore.sh"
"./bin/nim-client-petstore.sh"
"./bin/python-petstore-all.sh"
"./bin/openapi3/python-petstore.sh"
"./bin/php-petstore.sh"
"./bin/php-silex-petstore-server.sh"
"./bin/php-symfony-petstore.sh"
"./bin/php-lumen-petstore-server.sh"
"./bin/php-slim-server-petstore.sh"
"./bin/php-slim4-server-petstore.sh"
"./bin/php-ze-ph-petstore-server.sh"
"./bin/openapi3/php-petstore.sh"
"./bin/typescript-angularjs-petstore.sh"
"./bin/typescript-angular-petstore-all.sh"
"./bin/typescript-aurelia-petstore.sh"
"./bin/typescript-axios-petstore-all.sh"
"./bin/typescript-fetch-petstore-all.sh"
"./bin/typescript-inversify-petstore.sh"
"./bin/typescript-jquery-petstore-all.sh"
"./bin/typescript-node-petstore-all.sh"
"./bin/typescript-rxjs-petstore-all.sh"
"./bin/rust-server-petstore.sh"
"./bin/r-petstore.sh"
"./bin/haskell-http-client-petstore.sh"
"./bin/csharp-petstore.sh"
"./bin/csharp-netcore-petstore-all.sh"
"./bin/elixir-petstore.sh"
"./bin/openapi3/go-petstore.sh"
"./bin/go-experimental-petstore.sh"
"./bin/go-petstore.sh"
"./bin/go-petstore-withxml.sh"
"./bin/go-petstore-server.sh"
"./bin/go-gin-petstore-server.sh"
"./bin/groovy-petstore.sh"
"./bin/apex-petstore.sh"
"./bin/perl-petstore-all.sh"
"./bin/dart-jaguar-petstore.sh"
#"./bin/dart-dio-petstore.sh"
"./bin/dart-petstore.sh"
"./bin/dart2-petstore.sh"
"./bin/java-play-framework-petstore-server-all.sh"
"./bin/elm-petstore-all.sh"
"./bin/meta-codegen.sh"
"./bin/typescript.sh"
# OTHERS
"${root}/bin/utils/export_docs_generators.sh"
"${root}/bin/utils/copy-to-website.sh"
"${root}/bin/utils/export_generators_readme.sh")
"./bin/utils/export_docs_generators.sh"
"./bin/utils/copy-to-website.sh"
"./bin/utils/export_generators_readme.sh")
export JAVA_OPTS="${JAVA_OPTS} -Djava.awt.headless=true"
export JAVA_OPTS="-Djava.awt.headless=true"
if [ "true" = "$batch_mode" ]; then
if [ ! -f "$executable" ]; then
(cd "${root}" && mvn -B clean package -DskipTests=true -Dmaven.javadoc.skip=true)
for script in "${scripts[@]}"; do
if eval $script > /dev/null 2>&1; then
echo "Executed $script successfully!"
else
echo "ERROR: Failed to run $script"
exit 1
fi
# shellcheck disable=SC2086
java $JAVA_OPTS -jar "$executable" batch --includes-base-dir "${root}" --fail-fast -- "${root}"/bin/ci/*
else
for script in "${scripts[@]}"; do
if eval "$script" > /dev/null 2>&1; then
echo "Executed $script successfully!"
else
echo "ERROR: Failed to run $script"
exit 1
fi
done
fi
done
# Check:
if [ -n "$(git status --porcelain)" ]; then

View File

@@ -22,7 +22,7 @@ set -o pipefail
for cmd in {mvn,jq,curl}; do
if ! command -v ${cmd} > /dev/null; then
>&2 echo "This script requires '${cmd}' to be installed."
>&2 echo "This script requires '${cmd}' to be installed."
exit 1
fi
done
@@ -42,18 +42,7 @@ artifactid=openapi-generator-cli
ver=${OPENAPI_GENERATOR_VERSION:-$(latest.tag $ghrepo)}
jar=${artifactid}-${ver}.jar
# TODO: Remove OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR for release 5.0
if [ -n "${OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR}" ]; then
>&2 printf "[WARN] Variable OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR is misspelled.\nPlease change to OPENAPI_GENERATOR_DOWNLOAD_CACHE_DIR. This option will be removed in the 5.0 release.\n"
fi
cachedir=${OPENAPI_GENERATOR_DOWNLOAD_CACHE_DIR:-"$OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR"}
DIR=${cachedir:-"$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"}
if [ ! -d "${DIR}" ]; then
mkdir -p "${DIR}"
fi
DIR=${OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR:-"$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"}
if [ ! -f ${DIR}/${jar} ]; then
repo="central::default::https://repo1.maven.org/maven2/"

View File

@@ -1,8 +0,0 @@
call powershell -command "& '%~dp0\kotlin-client-gson.bat'"
call powershell -command "& '%~dp0\kotlin-client-nonpublic.bat'"
call powershell -command "& '%~dp0\kotlin-client-okhttp3.bat'"
call powershell -command "& '%~dp0\kotlin-client-petstore-multiplatform.bat'"
call powershell -command "& '%~dp0\kotlin-client-petstore.bat'"
call powershell -command "& '%~dp0\kotlin-client-string.bat'"
call powershell -command "& '%~dp0\kotlin-client-threetenbp.bat'"
call powershell -command "& '%~dp0\kotlin-client-nullable.bat'"

View File

@@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate --artifact-id "kotlin-petstore-gson" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --additional-properties serializationLibrary=gson -o samples\client\petstore\kotlin-gson
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate --artifact-id "kotlin-petstore-nonpublic" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --additional-properties nonPublicApi=true -o samples\client\petstore\kotlin-nonpublic
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --artifact-id "kotlin-petstore-nullable" --additional-properties nullableReturnType=true,serializableModel=true -o samples\client\petstore\kotlin-nullable
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate --artifact-id "kotlin-petstore-okhttp3" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --library jvm-okhttp3 -o samples\client\petstore\kotlin-okhttp3
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate --artifact-id "kotlin-petstore-client" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin -o samples\client\petstore\kotlin --additional-properties dateLibrary=java8,serializableModel=true
set ags=generate --artifact-id "kotlin-petstore-client" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin -o samples\client\petstore\kotlin
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --artifact-id "kotlin-petstore-string" --additional-properties dateLibrary=string,serializableModel=true -o samples\client\petstore\kotlin-string
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --artifact-id "kotlin-petstore-threetenbp" --additional-properties dateLibrary=threetenbp -o samples\client\petstore\kotlin-threetenbp
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -13,4 +13,3 @@ call .\bin\windows\typescript-angular-v7-not-provided-in-root.bat
call .\bin\windows\typescript-angular-v7-not-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v8-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v8-petstore-provided-in-root-with-prefixed-module-name.bat
call .\bin\windows\typescript-angular-v8-single-request-parameter.bat

View File

@@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g typescript-angular -c bin/typescript-angular-v8-petstore-provided-in-root-with-npm.json -o samples\client\petstore\typescript-angular-v8-provided-in-root\builds\single-request-parameter --additional-properties ngVersion=8.0.0,useSingleRequestParameter=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -57,6 +57,7 @@ The following generators are available:
* [swift2-deprecated (deprecated)](generators/swift2-deprecated.md)
* [swift3-deprecated (deprecated)](generators/swift3-deprecated.md)
* [swift4](generators/swift4.md)
* [typescript](generators/typescript.md)
* [typescript-angular](generators/typescript-angular.md)
* [typescript-angularjs](generators/typescript-angularjs.md)
* [typescript-aurelia](generators/typescript-aurelia.md)

View File

@@ -19,7 +19,6 @@ sidebar_label: csharp-netcore
|returnICollection|Return ICollection&lt;T&gt; instead of the concrete type.| |false|
|optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true|
|optionalAssemblyInfo|Generate AssemblyInfo.cs.| |true|
|optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false|
|optionalProjectFile|Generate {PackageName}.csproj.| |true|
|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.| |false|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|

View File

@@ -10,4 +10,3 @@ sidebar_label: go-server
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|sourceFolder|source folder for generated code| |go|
|serverPort|The network port the generated server binds to| |8080|
|featureCORS|Enable Cross-Origin Resource Sharing middleware| |false|

View File

@@ -11,4 +11,3 @@ sidebar_label: haskell
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|modelPackage|package for generated models| |null|
|apiPackage|package for generated api classes| |null|
|serveStatic|serve will serve files from the directory 'static'.| |true|

View File

@@ -16,7 +16,6 @@ sidebar_label: typescript-angular
|snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false|
|npmRepository|Use this property to set an url your private npmRepo in the package.json| |null|
|withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false|
|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |false|
|taggedUnions|Use discriminators to create tagged unions instead of extending interfaces.| |false|
|providedInRoot|Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0).| |false|
|ngVersion|The version of Angular.| |8.0.0|

View File

@@ -0,0 +1,17 @@
---
title: Config Options for typescript
sidebar_label: typescript
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
|supportsES6|Generate code that conforms to ES6.| |false|
|fileContentDataType|Specifies the type to use for the content of a file - i.e. Blob (Browser) / Buffer (node)| |Buffer|
|useRxJS|Enable this to internally use rxjs observables. If disabled, a stub is used instead. This is required for the 'angular' framework.| |false|
|platform|Specifies the platform the code should run on. The default is 'node' for the 'request' framework and 'browser' otherwise.| |null|
|framework|Specify the framework which should be used in the client code.|<dl><dt>**fetch-api**</dt><dd>fetch-api</dd><dt>**jquery**</dt><dd>jquery</dd><dl>|fetch-api|

View File

@@ -19,14 +19,6 @@ Supported tasks include:
See the [openapi-generator-maven-plugin README](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator-maven-plugin/README.md) for details related to configuring and using the Maven Plugin.
### sbt Integration
Please refer to https://github.com/upstart-commerce/sbt-openapi-generator
### Bazel Integration
Please refer to https://github.com/OpenAPITools/openapi-generator-bazel
### GitHub Integration
To push the auto-generated SDK to GitHub, we provide `git_push.sh` to streamline the process. For example:

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.2.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -72,34 +72,15 @@ public class Meta implements Runnable {
allowedValues = {"CLIENT", "SERVER", "DOCUMENTATION", "CONFIG", "OTHER"})
private String type = "OTHER";
@Option(name = {"-l", "--language"}, title = "language",
description = "the implementation language for the generator class",
allowedValues = {"java", "kotlin"}
)
private String language = "java";
@Override
public void run() {
final File targetDir = new File(outputFolder);
LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath());
String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator";
String kebabName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);
List<SupportingFile> supportingFiles = "kotlin".equals(language) ?
List<SupportingFile> supportingFiles =
ImmutableList.of(
new SupportingFile("kotlin/build_gradle.mustache", "", "build.gradle.kts"),
new SupportingFile("kotlin/gradle.properties", "", "gradle.properties"),
new SupportingFile("kotlin/settings.mustache", "", "settings.gradle"),
new SupportingFile("kotlin/generatorClass.mustache", on(File.separator).join("src/main/kotlin", asPath(targetPackage)), mainClass.concat(".kt")),
new SupportingFile("kotlin/generatorClassTest.mustache", on(File.separator).join("src/test/kotlin", asPath(targetPackage)), mainClass.concat("Test.kt")),
new SupportingFile("kotlin/README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()))
: ImmutableList.of(
new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
@@ -116,7 +97,6 @@ public class Meta implements Runnable {
.put("generatorPackage", targetPackage)
.put("generatorClass", mainClass)
.put("name", name)
.put("kebabName", kebabName)
.put("generatorType", type)
.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass)
.put("openapiGeneratorVersion", currentVersion).build();

View File

@@ -6,7 +6,7 @@
<artifactId>openapi-generator-project</artifactId>
<groupId>org.openapitools</groupId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.2.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -103,9 +103,7 @@ public class WorkflowSettings {
builder.strictSpecBehavior = copy.isStrictSpecBehavior();
builder.templatingEngineName = copy.getTemplatingEngineName();
builder.ignoreFileOverride = copy.getIgnoreFileOverride();
// this, and any other collections, must be mutable in the builder.
builder.systemProperties = new HashMap<>(copy.getSystemProperties());
builder.systemProperties = ImmutableMap.copyOf(copy.getSystemProperties());
// force builder "with" methods to invoke side effects
builder.withTemplateDir(copy.getTemplateDir());
@@ -274,8 +272,6 @@ public class WorkflowSettings {
private String templateDir;
private String templatingEngineName = DEFAULT_TEMPLATING_ENGINE_NAME;
private String ignoreFileOverride;
// NOTE: All collections must be mutable in the builder, and copied to a new immutable collection in .build()
private Map<String, String> systemProperties = new HashMap<>();;
private Builder() {

View File

@@ -19,7 +19,6 @@ package org.openapitools.codegen.config;
import org.testng.annotations.Test;
import java.nio.file.Paths;
import java.util.Map;
import static org.testng.Assert.*;
@@ -49,25 +48,6 @@ public class WorkflowSettingsTest {
assertTrue(settings.isStrictSpecBehavior());
}
@Test
public void newBuilderFromCopyShouldMutateSystemProperties(){
WorkflowSettings original = WorkflowSettings.newBuilder()
.withOutputDir("output")
.withVerbose(true)
.withSkipOverwrite(false)
.withSystemProperty("first", "1st")
.build();
WorkflowSettings modified = WorkflowSettings.newBuilder(original)
.withSystemProperty("second", "2nd")
.build();
Map<String, String> properties = modified.getSystemProperties();
assertEquals(properties.size(), 2, "System Properties map should allow mutation when invoked via copy constructor");
assertEquals(properties.getOrDefault("first", ""), "1st");
assertEquals(properties.getOrDefault("second", ""), "2nd");
}
private void assertOnChangesToDefaults(WorkflowSettings defaults) {
WorkflowSettings settings = WorkflowSettings.newBuilder()
.withOutputDir("output")

View File

@@ -45,7 +45,7 @@ compileJava.dependsOn tasks.openApiGenerate
[source,group]
----
plugins {
id "org.openapi.generator" version "4.2.1"
id "org.openapi.generator" version "4.1.1"
}
----
@@ -61,7 +61,7 @@ buildscript {
// url "https://plugins.gradle.org/m2/"
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:4.2.0"
classpath "org.openapitools:openapi-generator-gradle-plugin:4.1.1"
}
}
@@ -626,7 +626,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath('org.openapitools:openapi-generator-gradle-plugin:4.2.0') {
classpath('org.openapitools:openapi-generator-gradle-plugin:4.1.1') {
exclude group: 'com.google.guava'
}
}

View File

@@ -1,5 +1,5 @@
buildscript {
ext.kotlin_version = '1.3.20'
ext.kotlin_version = '1.2.61'
repositories {
mavenLocal()
mavenCentral()
@@ -15,7 +15,7 @@ buildscript {
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "gradle.plugin.org.gradle.kotlin:gradle-kotlin-dsl-plugins:1.1.3"
classpath "gradle.plugin.org.gradle.kotlin:gradle-kotlin-dsl-plugins:1.0-rc-3"
classpath "com.gradle.publish:plugin-publish-plugin:0.10.1"
classpath "io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.20.0"
classpath "de.marcphilipp.gradle:nexus-publish-plugin:0.2.0"

View File

@@ -1,5 +1,5 @@
# RELEASE_VERSION
openApiGeneratorVersion=4.2.1
openApiGeneratorVersion=4.2.0-SNAPSHOT
# /RELEASE_VERSION
# BEGIN placeholders

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip
distributionUrl=https\://downloads.gradle.org/distributions/gradle-4.10.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.2.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>
@@ -17,7 +17,7 @@
<properties>
<skipNexusStagingDeployMojo>true</skipNexusStagingDeployMojo>
<gradleVersion>5.2.1</gradleVersion>
<gradleVersion>4.10.2</gradleVersion>
</properties>
<pluginRepositories>

View File

@@ -11,12 +11,11 @@ gradle openApiGenerate
gradle openApiMeta
gradle openApiValidate
gradle buildGoSdk
gradle buildDotnetSdk
gradle generateGoWithInvalidSpec
```
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=4.2.1 openApiValidate
gradle -PopenApiGeneratorVersion=4.1.1 openApiValidate
```

View File

@@ -65,20 +65,6 @@ task buildGoSdk(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTas
]
}
task buildDotnetSdk(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask){
generatorName = "csharp-netcore"
inputSpec = "$rootDir/petstore-v3.0.yaml".toString()
additionalProperties = [
packageGuid: "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}",
useCompareNetObjects: "true"
]
outputDir = "$buildDir/csharp-netcore".toString()
systemProperties = [
models: "",
apis : "",
]
}
task generateGoWithInvalidSpec(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask){
validateSpec = true
generatorName = "go"

View File

@@ -1,3 +1,3 @@
# RELEASE_VERSION
openApiGeneratorVersion=4.2.0
openApiGeneratorVersion=4.1.1
# /RELEASE_VERSION

View File

@@ -18,7 +18,6 @@ package org.openapitools.generator.gradle.plugin.extensions
import org.gradle.api.Project
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.mapProperty
import org.gradle.kotlin.dsl.property
/**
@@ -67,7 +66,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Sets specified system properties.
*/
val systemProperties = project.objects.mapProperty<String, String>()
val systemProperties = project.objects.property<Map<String, String>>()
/**
* Path to json configuration file.
@@ -109,22 +108,22 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Sets instantiation type mappings.
*/
val instantiationTypes = project.objects.mapProperty<String, String>()
val instantiationTypes = project.objects.property<Map<String, String>>()
/**
* Sets mappings between OpenAPI spec types and generated code types.
*/
val typeMappings = project.objects.mapProperty<String, String>()
val typeMappings = project.objects.property<Map<String, String>>()
/**
* Sets additional properties that can be referenced by the mustache templates.
*/
val additionalProperties = project.objects.mapProperty<String, String>()
val additionalProperties = project.objects.property<Map<String, String>>()
/**
* Sets server variable for server URL template substitution, in the format of name=value,name=value.
*/
val serverVariables = project.objects.mapProperty<String, String>()
val serverVariables = project.objects.property<Map<String, String>>()
/**
* Specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double.
@@ -134,7 +133,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Specifies mappings between a given class and the import that should be used for that class.
*/
val importMappings = project.objects.mapProperty<String, String>()
val importMappings = project.objects.property<Map<String, String>>()
/**
* Root package for generated code.
@@ -189,7 +188,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used.
*/
val reservedWordsMappings = project.objects.mapProperty<String, String>()
val reservedWordsMappings = project.objects.property<Map<String, String>>()
/**
* Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation.
@@ -305,7 +304,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* A map of options specific to a generator.
*/
val configOptions = project.objects.mapProperty<String, String>()
val configOptions = project.objects.property<Map<String, String>>()
init {
applyDefaults()

View File

@@ -24,7 +24,6 @@ import org.gradle.api.tasks.TaskAction
import org.gradle.internal.logging.text.StyledTextOutput
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.mapProperty
import org.gradle.kotlin.dsl.property
import org.openapitools.codegen.CodegenConstants
import org.openapitools.codegen.DefaultGenerator
@@ -91,7 +90,7 @@ open class GenerateTask : DefaultTask() {
* Sets specified system properties.
*/
@get:Internal
val systemProperties = project.objects.mapProperty<String, String>()
val systemProperties = project.objects.property<Map<String, String>>()
/**
* Path to json configuration file.
@@ -141,27 +140,27 @@ open class GenerateTask : DefaultTask() {
* Sets instantiation type mappings.
*/
@get:Internal
val instantiationTypes = project.objects.mapProperty<String, String>()
val instantiationTypes = project.objects.property<Map<String, String>>()
/**
* Sets mappings between OpenAPI spec types and generated code types.
*/
@get:Internal
val typeMappings = project.objects.mapProperty<String, String>()
val typeMappings = project.objects.property<Map<String, String>>()
/**
* Sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value.
* You can also have multiple occurrences of this option.
*/
@get:Internal
val additionalProperties = project.objects.mapProperty<String, String>()
val additionalProperties = project.objects.property<Map<String, String>>()
/**
* Sets server variable for server URL template substitution, in the format of name=value,name=value.
* You can also have multiple occurrences of this option.
*/
@get:Internal
val serverVariables = project.objects.mapProperty<String, String>()
val serverVariables = project.objects.property<Map<String, String>>()
/**
* Specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double.
@@ -173,7 +172,7 @@ open class GenerateTask : DefaultTask() {
* Specifies mappings between a given class and the import that should be used for that class.
*/
@get:Internal
val importMappings = project.objects.mapProperty<String, String>()
val importMappings = project.objects.property<Map<String, String>>()
/**
* Root package for generated code.
@@ -239,7 +238,7 @@ open class GenerateTask : DefaultTask() {
* Specifies how a reserved name should be escaped to.
*/
@get:Internal
val reservedWordsMappings = project.objects.mapProperty<String, String>()
val reservedWordsMappings = project.objects.property<Map<String, String>>()
/**
* Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation.
@@ -373,7 +372,7 @@ open class GenerateTask : DefaultTask() {
* A dynamic map of options specific to a generator.
*/
@get:Internal
val configOptions = project.objects.mapProperty<String, String>()
val configOptions = project.objects.property<Map<String, String>>()
private fun <T : Any?> Property<T>.ifNotEmpty(block: Property<T>.(T) -> Unit) {
if (isPresent) {

View File

@@ -12,7 +12,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.1.1</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.1.3-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -1,237 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>sample-project</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>sample-project</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<!-- activate the plugin -->
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>
<id>default</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<!-- specify the swagger yaml -->
<inputSpec>${project.basedir}/swagger.yaml</inputSpec>
<!-- target to generate java client code -->
<generatorName>kotlin</generatorName>
<!-- hint: if you want to generate java server code, e.g. based on Spring Boot,
you can use the following target: <generatorName>spring</generatorName> -->
<!-- pass any necessary config options -->
<configOptions>
<serializableModel>true</serializableModel>
</configOptions>
</configuration>
</execution>
<execution>
<id>kotlin</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<!-- specify the swagger yaml -->
<inputSpec>https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml
</inputSpec>
<!-- target to generate java client code -->
<generatorName>kotlin</generatorName>
<!-- hint: if you want to generate java server code, e.g. based on Spring Boot,
you can use the following target: <generatorName>spring</generatorName> -->
<!-- pass any necessary config options -->
<configOptions>
<serializableModel>true</serializableModel>
</configOptions>
<output>${project.build.directory}/generated-sources/kotlin</output>
<apiPackage>kotlintest.org.openapitools.client.api</apiPackage>
<modelPackage>kotlintest.org.openapitools.client.model</modelPackage>
<invokerPackage>kotlintest.org.openapitools.client</invokerPackage>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<proc>none</proc>
</configuration>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<configuration>
<jvmTarget>${kotlinJvmTarget}</jvmTarget>
<javacOptions/>
</configuration>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.build.directory}/generated-sources/kotlin/src/main/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<pluginRepositories>
<pluginRepository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<!-- dependencies are needed for the client being generated -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- You can find the dependencies for the library configuation you chose by looking in JavaClientCodegen.
Then find the corresponding dependency on Maven Central, and set the versions in the property section below -->
<!-- HTTP client: jersey-client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
<!-- Joda time: if you use it -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- Base64 encoding that works in both JVM and Android -->
<dependency>
<groupId>com.brsanthu</groupId>
<artifactId>migbase64</artifactId>
<version>${migbase64.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-kotlin</artifactId>
<version>${moshi-kotlin.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-adapters</artifactId>
<version>${moshi-kotlin.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.2.2</version>
</dependency>
</dependencies>
<properties>
<swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>2.27</jersey-version>
<jackson-version>2.8.9</jackson-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
<jodatime-version>2.7</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version>
<kotlin.version>1.3.50</kotlin.version>
<kotlinJvmTarget>1.8</kotlinJvmTarget>
<moshi-kotlin.version>1.8.0</moshi-kotlin.version>
<migbase64.version>2.2</migbase64.version>
</properties>
</project>

View File

@@ -19,7 +19,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.1.3-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<dependencies>
<dependency>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.1.1</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.1.1</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -5,7 +5,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.2.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.2.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.2.1</version>
<version>4.2.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -30,8 +30,8 @@ public class CodegenOperation {
isResponseBinary = false, isResponseFile = false, hasReference = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful, isDeprecated, isCallbackRequest;
public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse;
public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse;
public CodegenDiscriminator discriminator;
public List<Map<String, String>> consumes, produces, prioritizedContentTypes;
public List<CodegenServer> servers = new ArrayList<CodegenServer>();

View File

@@ -22,6 +22,7 @@ import java.util.*;
public class CodegenResponse {
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String code, message;
public boolean isSuccessCode;
public boolean hasMore;
public List<Map<String, Object>> examples;
public String dataType, baseType, containerType;

View File

@@ -17,7 +17,6 @@
package org.openapitools.codegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@@ -39,7 +38,7 @@ public class CodegenSecurity {
// Oauth specific
public String flow, authorizationUrl, tokenUrl;
public List<Map<String, Object>> scopes;
public Boolean isCode, isPassword, isApplication, isImplicit;
public Boolean isCode, isPassword, isApplication, isImplicit, hasScopes;
@Override
public String toString() {
@@ -101,47 +100,4 @@ public class CodegenSecurity {
isImplicit,
scopes);
}
// Return a copy of the security object, filtering out any scopes from the passed-in list.
public CodegenSecurity filterByScopeNames(List<String> filterScopes) {
CodegenSecurity filteredSecurity = new CodegenSecurity();
// Copy all fields except the scopes.
filteredSecurity.name = name;
filteredSecurity.type = type;
filteredSecurity.hasMore = false;
filteredSecurity.isBasic = isBasic;
filteredSecurity.isBasicBasic = isBasicBasic;
filteredSecurity.isBasicBearer = isBasicBearer;
filteredSecurity.isApiKey = isApiKey;
filteredSecurity.isOAuth = isOAuth;
filteredSecurity.keyParamName = keyParamName;
filteredSecurity.isCode = isCode;
filteredSecurity.isImplicit = isImplicit;
filteredSecurity.isApplication = isApplication;
filteredSecurity.isPassword = isPassword;
filteredSecurity.isKeyInCookie = isKeyInCookie;
filteredSecurity.isKeyInHeader = isKeyInHeader;
filteredSecurity.isKeyInQuery = isKeyInQuery;
filteredSecurity.flow = flow;
filteredSecurity.tokenUrl = tokenUrl;
filteredSecurity.authorizationUrl = authorizationUrl;
// It is not possible to deep copy the extensions, as we have no idea what types they are.
// So the filtered method *will* refer to the original extensions, if any.
filteredSecurity.vendorExtensions = new HashMap<String, Object>(vendorExtensions);
List<Map<String, Object>> returnedScopes = new ArrayList<Map<String, Object>>();
Map<String, Object> lastScope = null;
for (String filterScopeName : filterScopes) {
for (Map<String, Object> scope : scopes) {
String name = (String) scope.get("scope");
if (filterScopeName.equals(name)) {
returnedScopes.add(scope);
lastScope = scope;
break;
}
}
}
filteredSecurity.scopes = returnedScopes;
return filteredSecurity;
}
}

View File

@@ -2547,7 +2547,8 @@ public class DefaultCodegen implements CodegenConfig {
op.examples = new ExampleGenerator(schemas, this.openAPI).generateFromResponseSchema(exampleStatusCode, responseSchema, getProducesInfo(this.openAPI, operation));
op.defaultResponse = toDefaultValue(responseSchema);
op.returnType = cm.dataType;
op.hasReference = schemas.containsKey(op.returnBaseType);
op.returnFormat = cm.dataFormat;
op.hasReference = schemas != null && schemas.containsKey(op.returnBaseType);
// lookup discriminator
Schema schema = schemas.get(op.returnBaseType);
@@ -2869,6 +2870,7 @@ public class DefaultCodegen implements CodegenConfig {
r.code = "0";
} else {
r.code = responseCode;
r.isSuccessCode = r.code.startsWith("2");
}
Schema responseSchema;
if (this.openAPI != null && this.openAPI.getComponents() != null) {
@@ -3374,7 +3376,7 @@ public class DefaultCodegen implements CodegenConfig {
return false;
}
}
// TODO revise below as it should be replaced by ModelUtils.isFileSchema(parameterSchema)
public boolean isDataTypeFile(String dataType) {
if (dataType != null) {

View File

@@ -1057,21 +1057,55 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes);
if (authMethods != null && !authMethods.isEmpty()) {
List<CodegenSecurity> fullAuthMethods = config.fromSecurity(authMethods);
codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, securities);
codegenOperation.hasAuthMethods = true;
} else {
if (authMethods == null || authMethods.isEmpty()) {
authMethods = getAuthMethods(globalSecurities, securitySchemes);
if (authMethods != null && !authMethods.isEmpty()) {
List<CodegenSecurity> fullAuthMethods = config.fromSecurity(authMethods);
codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, globalSecurities);
codegenOperation.hasAuthMethods = true;
}
}
if (authMethods != null && !authMethods.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(authMethods);
List<Map<String, Object>> scopes = new ArrayList<Map<String, Object>>();
if (codegenOperation.authMethods != null) {
for (CodegenSecurity security : codegenOperation.authMethods) {
if (security != null && security.isBasicBearer != null && security.isBasicBearer &&
securities != null) {
for (SecurityRequirement req : securities) {
if (req == null) continue;
for (String key : req.keySet()) {
if (security.name != null && key.equals(security.name)) {
int count = 0;
for (String sc : req.get(key)) {
Map<String, Object> scope = new HashMap<String, Object>();
scope.put("scope", sc);
scope.put("description", "");
count++;
if (req.get(key) != null && count < req.get(key).size()) {
scope.put("hasMore", "true");
} else {
scope.put("hasMore", null);
}
scopes.add(scope);
}
//end this inner for
break;
}
}
}
security.hasScopes = scopes.size() > 0;
security.scopes = scopes;
}
}
}
codegenOperation.hasAuthMethods = true;
}
/* TODO need to revise the logic below
Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents().getSecuritySchemes();
if (securitySchemeMap != null && !securitySchemeMap.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(securitySchemeMap);
codegenOperation.hasAuthMethods = true;
}
*/
} catch (Exception ex) {
String msg = "Could not process operation:\n" //
+ " Tag: " + tag + "\n"//
@@ -1277,40 +1311,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
.scopes(newScopes);
}
private List<CodegenSecurity> filterAuthMethods(List<CodegenSecurity> authMethods, List<SecurityRequirement> securities) {
if (securities == null || securities.isEmpty() || authMethods == null) {
return authMethods;
}
List<CodegenSecurity> result = new ArrayList<CodegenSecurity>();
for (CodegenSecurity security : authMethods) {
boolean filtered = false;
if (security != null && security.scopes != null) {
for (SecurityRequirement requirement : securities) {
List<String> opScopes = requirement.get(security.name);
if (opScopes != null) {
// We have operation-level scopes for this method, so filter the auth method to
// describe the operation auth method with only the scopes that it requires.
// We have to create a new auth method instance because the original object must
// not be modified.
CodegenSecurity opSecurity = security.filterByScopeNames(opScopes);
result.add(opSecurity);
filtered = true;
break;
}
}
}
// If we didn't get a filtered version, then we can keep the original auth method.
if (!filtered) {
result.add(security);
}
}
return result;
}
private boolean hasOAuthMethods(List<CodegenSecurity> authMethods) {
for (CodegenSecurity cs : authMethods) {
if (Boolean.TRUE.equals(cs.isOAuth)) {

View File

@@ -300,17 +300,12 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
String port = URLPathUtils.getPort(url, "");
String host = url.getHost();
String scheme = url.getProtocol();
if(!port.isEmpty()) {
this.additionalProperties.put("serverPort", port);
}
if(!host.isEmpty()) {
this.additionalProperties.put("serverHost", host);
}
if(!scheme.isEmpty()) {
this.additionalProperties.put("scheme", scheme);
}
}
@Override

View File

@@ -434,19 +434,19 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
}
if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) {
this.setSerializableModel(getBooleanOption(CodegenConstants.SERIALIZABLE_MODEL));
this.setSerializableModel(Boolean.valueOf((String) additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL)));
} else {
additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel);
}
if (additionalProperties.containsKey(CodegenConstants.PARCELIZE_MODELS)) {
this.setParcelizeModels(getBooleanOption(CodegenConstants.PARCELIZE_MODELS));
this.setParcelizeModels(Boolean.valueOf((String) additionalProperties.get(CodegenConstants.PARCELIZE_MODELS)));
} else {
additionalProperties.put(CodegenConstants.PARCELIZE_MODELS, parcelizeModels);
}
if (additionalProperties.containsKey(CodegenConstants.NON_PUBLIC_API)) {
this.setNonPublicApi(getBooleanOption(CodegenConstants.NON_PUBLIC_API));
this.setNonPublicApi(Boolean.valueOf((String) additionalProperties.get(CodegenConstants.NON_PUBLIC_API)));
} else {
additionalProperties.put(CodegenConstants.NON_PUBLIC_API, nonPublicApi);
}
@@ -458,18 +458,6 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
additionalProperties.put("modelDocPath", modelDocPath);
}
private boolean getBooleanOption(String key) {
final Object booleanValue = additionalProperties.get(key);
Boolean result = Boolean.FALSE;
if (booleanValue instanceof Boolean) {
result = (Boolean) booleanValue;
} else if (booleanValue instanceof String) {
result = Boolean.parseBoolean((String) booleanValue);
}
additionalProperties.put(key, result);
return result;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
@@ -513,7 +501,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
public void setSerializableModel(boolean serializableModel) {
this.serializableModel = serializableModel;
}
public boolean nonPublicApi() {
return nonPublicApi;
}

View File

@@ -34,7 +34,6 @@ import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
@@ -442,16 +441,12 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
if (ModelUtils.isComposedSchema(p)) {
return openAPIType;
} else if (typeMapping.containsKey(openAPIType)) {
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type)) {
if (languageSpecificPrimitives.contains(type))
return type;
}
} else {
} else
type = openAPIType;
}
return toModelName(type);
}
@@ -565,20 +560,6 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
}
@Override
protected void addImport(CodegenModel m, String type) {
if (type == null) {
return;
}
String[] parts = type.split("( [|&] )|[<>]");
for (String s : parts) {
if (needToImport(s)) {
m.imports.add(s);
}
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
@@ -720,43 +701,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
List<String> types = composedSchema.getAnyOf().stream().map(schema -> {
String schemaType = getSchemaType(schema);
if (ModelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">";
}
return schemaType;
}).distinct().collect(Collectors.toList());
return String.join(" | ", types);
return String.join(" | ", names);
}
@Override
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
List<String> types = composedSchema.getOneOf().stream().map(schema -> {
String schemaType = getSchemaType(schema);
if (ModelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">";
}
return schemaType;
}).distinct().collect(Collectors.toList());
return String.join(" | ", types);
}
@Override
public String toAllOfName(List<String> names, ComposedSchema composedSchema) {
List<String> types = composedSchema.getAllOf().stream().map(schema -> {
String schemaType = getSchemaType(schema);
if (ModelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">";
}
return schemaType;
}).distinct().collect(Collectors.toList());
return String.join(" & ", types);
return String.join(" | ", names);
}
}

View File

@@ -81,10 +81,10 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code
if (Files.isRegularFile(filePathToInclude)) {
LOGGER.debug(
"including " + ++includeCount + ". file into markup from: " + filePathToInclude.toString());
out.write("\ninclude::" + relativeFileName + "[opts=optional]\n");
out.write("\ninclude::" + relativeFileName + "[]\n");
} else {
LOGGER.debug(++notFoundCount + ". file not found, skip include for: " + filePathToInclude.toString());
out.write("\n// markup not found, no include ::" + relativeFileName + "[opts=optional]\n");
out.write("\n// markup not found, no include ::" + relativeFileName + "[]\n");
}
}
}
@@ -158,8 +158,6 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code
*/
static String sanitize(final String name) {
String sanitized = name == null ? "" : name.trim();
sanitized = sanitized.replace("//", "/"); // rest paths may or may not end with slashes, leading to redundant
// path separators.
return sanitized.startsWith(File.separator) || sanitized.startsWith("/") ? sanitized.substring(1) : sanitized;
}
@@ -202,10 +200,10 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code
cliOptions.add(new CliOption(SNIPPET_DIR,
"path with includable markup snippets (e.g. test output generated by restdoc, default: .")
.defaultValue("."));
.defaultValue("."));
cliOptions.add(new CliOption(SPEC_DIR,
"path with includable markup spec files (e.g. handwritten additional docs, default: .")
.defaultValue(".."));
.defaultValue(".."));
additionalProperties.put("appName", "OpenAPI Sample description");
additionalProperties.put("appDescription", "A sample OpenAPI documentation");

View File

@@ -185,10 +185,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC,
this.optionalAssemblyInfoFlag);
addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES,
CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC,
this.optionalEmitDefaultValuesFlag);
addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE,
CodegenConstants.OPTIONAL_PROJECT_FILE_DESC,
this.optionalProjectFileFlag);
@@ -374,8 +370,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
postProcessPattern(property.pattern, property.vendorExtensions);
postProcessEmitDefaultValue(property.vendorExtensions);
super.postProcessModelProperty(model, property);
}
@@ -409,7 +403,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override
public void postProcessParameter(CodegenParameter parameter) {
postProcessPattern(parameter.pattern, parameter.vendorExtensions);
postProcessEmitDefaultValue(parameter.vendorExtensions);
super.postProcessParameter(parameter);
if (!parameter.required && nullableType.contains(parameter.dataType)) { //optional
@@ -453,10 +446,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
}
public void postProcessEmitDefaultValue(Map<String, Object> vendorExtensions) {
vendorExtensions.put("x-emit-default-value", optionalEmitDefaultValuesFlag);
}
@Override
public Mustache.Compiler processCompiler(Mustache.Compiler compiler) {
// To avoid unexpected behaviors when options are passed programmatically such as { "supportsAsync": "" }
@@ -476,13 +465,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
* if (additionalProperties.containsKey(prop)) convertPropertyToBooleanAndWriteBack(prop);
*/
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)) {
setOptionalEmitDefaultValuesFlag(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES));
} else {
additionalProperties.put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, optionalEmitDefaultValuesFlag);
}
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
}
@@ -628,10 +610,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
this.optionalAssemblyInfoFlag = flag;
}
public void setOptionalEmitDefaultValuesFlag(boolean flag){
this.optionalEmitDefaultValuesFlag = flag;
}
public void setOptionalProjectFileFlag(boolean flag) {
this.optionalProjectFileFlag = flag;
}

View File

@@ -26,47 +26,12 @@ import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
// import static org.openapitools.codegen.utils.StringUtils.camelize;
// import static org.openapitools.codegen.utils.StringUtils.underscore;
// import java.io.BufferedReader;
// import java.io.File;
// import java.io.FileInputStream;
// import java.io.InputStreamReader;
// import java.nio.charset.Charset;
// import java.util.ArrayList;
// import java.util.Arrays;
// import java.util.HashMap;
// import java.util.HashSet;
// import java.util.List;
// import java.util.Map;
// import java.util.Set;
// import javax.xml.validation.Schema;
// import org.apache.commons.io.FilenameUtils;
// import org.openapitools.codegen.CodegenConfig;
// import org.openapitools.codegen.CodegenConstants;
// import org.openapitools.codegen.CodegenModel;
// import org.openapitools.codegen.CodegenProperty;
// import org.openapitools.codegen.CodegenType;
// import org.openapitools.codegen.DefaultCodegen;
// import org.openapitools.codegen.utils.ModelUtils;
// import org.openapitools.codegen.utils.StringUtils;
// import org.slf4j.LoggerFactory;
// import io.swagger.v3.oas.models.media.ArraySchema;
public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DartClientCodegen.class);
@@ -90,7 +55,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
public DartClientCodegen() {
super();
// clear import mapping (from default generator) as dart does not use it at the moment
// clear import mapping (from default generator) as dart does not use it
// at the moment
importMapping.clear();
outputFolder = "generated-code/dart";
@@ -105,15 +71,19 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
modelTestTemplateFiles.put("model_test.mustache", ".dart");
apiTestTemplateFiles.put("api_test.mustache", ".dart");
List<String> reservedWordsList = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"), Charset.forName("UTF-8")));
while(reader.ready()) { reservedWordsList.add(reader.readLine()); }
reader.close();
} catch (Exception e) {
LOGGER.error("Error reading dart keywords. Exception: {}", e.getMessage());
}
setReservedWordsLowerCase(reservedWordsList);
setReservedWordsLowerCase(
Arrays.asList(
"abstract", "as", "assert", "async", "async*", "await",
"break", "case", "catch", "class", "const", "continue",
"default", "deferred", "do", "dynamic", "else", "enum",
"export", "external", "extends", "factory", "false", "final",
"finally", "for", "get", "if", "implements", "import", "in",
"is", "library", "new", "null", "operator", "part", "rethrow",
"return", "set", "static", "super", "switch", "sync*", "this",
"throw", "true", "try", "typedef", "var", "void", "while",
"with", "yield", "yield*", "hide", "interface", "mixin", "on",
"show", "async")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(

View File

@@ -39,7 +39,6 @@ public class GoServerCodegen extends AbstractGoCodegen {
protected int serverPort = 8080;
protected String projectName = "openapi-server";
protected String sourceFolder = "go";
protected Boolean corsFeatureEnabled = false;
public GoServerCodegen() {
@@ -47,20 +46,15 @@ public class GoServerCodegen extends AbstractGoCodegen {
// set the output folder here
outputFolder = "generated-code/go";
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)
.defaultValue(sourceFolder));
CliOption optServerPort = new CliOption("serverPort", "The network port the generated server binds to");
optServerPort.setType("int");
optServerPort.defaultValue(Integer.toString(serverPort));
cliOptions.add(optServerPort);
CliOption optFeatureCORS = new CliOption("featureCORS", "Enable Cross-Origin Resource Sharing middleware");
optFeatureCORS.setType("bool");
optFeatureCORS.defaultValue(corsFeatureEnabled.toString());
cliOptions.add(optFeatureCORS);
/*
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
@@ -117,8 +111,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
@@ -129,31 +123,25 @@ public class GoServerCodegen extends AbstractGoCodegen {
setPackageName("openapi");
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
this.setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
} else {
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder);
}
if (additionalProperties.containsKey("serverPort") && additionalProperties.get("serverPort") instanceof Integer) {
this.setServerPort((int) additionalProperties.get("serverPort"));
} else {
additionalProperties.put("serverPort", serverPort);
}
if (additionalProperties.containsKey("featureCORS")) {
this.setFeatureCORS(convertPropertyToBooleanAndWriteBack("featureCORS"));
} else {
additionalProperties.put("featureCORS", corsFeatureEnabled);
}
modelPackage = packageName;
apiPackage = packageName;
@@ -263,7 +251,7 @@ public class GoServerCodegen extends AbstractGoCodegen {
public String modelFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@@ -274,9 +262,5 @@ public class GoServerCodegen extends AbstractGoCodegen {
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
}
public void setFeatureCORS(Boolean featureCORS) {
this.corsFeatureEnabled = featureCORS;
}
}
}

View File

@@ -43,10 +43,6 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
protected String apiVersion = "0.0.1";
private static final Pattern LEADING_UNDERSCORE = Pattern.compile("^_+");
public static final String PROP_SERVE_STATIC = "serveStatic";
public static final String PROP_SERVE_STATIC_DESC = "serve will serve files from the directory 'static'.";
public static final Boolean PROP_SERVE_STATIC_DEFAULT = Boolean.TRUE;
/**
* Configures the type of generator.
*
@@ -187,15 +183,6 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(new CliOption(PROP_SERVE_STATIC, PROP_SERVE_STATIC_DESC).defaultValue(PROP_SERVE_STATIC_DEFAULT.toString()));
}
public void setBooleanProperty(String property, Boolean defaultValue) {
if (additionalProperties.containsKey(property)) {
additionalProperties.put(property, convertPropertyToBoolean(property));
} else {
additionalProperties.put(property, defaultValue);
}
}
@Override
@@ -205,8 +192,6 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
if (StringUtils.isEmpty(System.getenv("HASKELL_POST_PROCESS_FILE"))) {
LOGGER.info("Hint: Environment variable HASKELL_POST_PROCESS_FILE not defined so the Haskell code may not be properly formatted. To define it, try 'export HASKELL_POST_PROCESS_FILE=\"$HOME/.local/bin/hfmt -w\"' (Linux/Mac)");
}
setBooleanProperty(PROP_SERVE_STATIC, PROP_SERVE_STATIC_DEFAULT);
}
/**

View File

@@ -30,8 +30,6 @@ import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class KotlinClientCodegen extends AbstractKotlinCodegen {
@@ -168,7 +166,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
if (isJVMLibrary()) {
additionalProperties.put(JVM, true);
if (JVM_OKHTTP4.equals(getLibrary())) {
additionalProperties.put(JVM_OKHTTP4, true);
} else if (JVM_OKHTTP3.equals(getLibrary())) {
@@ -188,10 +186,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
supportingFiles.add(new SupportingFile("infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt"));
supportingFiles.add(new SupportingFile("infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt"));
supportingFiles.add(new SupportingFile("infrastructure/UUIDAdapter.kt.mustache", infrastructureFolder, "UUIDAdapter.kt"));
if (getSerializationLibrary() == SERIALIZATION_LIBRARY_TYPE.gson) {
supportingFiles.add(new SupportingFile("infrastructure/DateAdapter.kt.mustache", infrastructureFolder,
"DateAdapter.kt"));
}
} else if (MULTIPLATFORM.equals(getLibrary())) {
additionalProperties.put(MULTIPLATFORM, true);
@@ -293,20 +287,15 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
CodegenModel cm = (CodegenModel) mo.get("model");
// escape the variable base name for use as a string literal
List<CodegenProperty> vars = Stream.of(
cm.vars,
cm.allVars,
cm.optionalVars,
cm.requiredVars,
cm.readOnlyVars,
cm.readWriteVars,
cm.parentVars
)
.flatMap(List::stream)
.collect(Collectors.toList());
for (CodegenProperty var : vars) {
var.vendorExtensions.put(VENDOR_EXTENSION_BASE_NAME_LITERAL, var.baseName.replace("$", "\\$"));
if (cm.requiredVars != null) {
for (CodegenProperty var : cm.requiredVars) {
var.vendorExtensions.put(VENDOR_EXTENSION_BASE_NAME_LITERAL, var.baseName.replace("$", "\\$"));
}
}
if (cm.optionalVars != null) {
for (CodegenProperty var : cm.optionalVars) {
var.vendorExtensions.put(VENDOR_EXTENSION_BASE_NAME_LITERAL, var.baseName.replace("$", "\\$"));
}
}
}

View File

@@ -26,8 +26,6 @@ import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.features.BeanValidationFeatures;
import org.openapitools.codegen.languages.features.OptionalFeatures;
import org.openapitools.codegen.languages.features.PerformBeanValidationFeatures;
import org.openapitools.codegen.templating.mustache.SplitStringLambda;
import org.openapitools.codegen.templating.mustache.TrimWhitespaceLambda;
import org.openapitools.codegen.utils.URLPathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -465,10 +463,6 @@ public class SpringCodegen extends AbstractJavaCodegen
(Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement("\\\""))));
additionalProperties.put("lambdaRemoveLineBreak",
(Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\\r|\\n", "")));
additionalProperties.put("lambdaTrimWhitespace", new TrimWhitespaceLambda());
additionalProperties.put("lambdaSplitString", new SplitStringLambda());
}
@Override

View File

@@ -40,11 +40,8 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$";
private static final String DEFAULT_IMPORT_PREFIX = "./";
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter";
public static final String TAGGED_UNIONS = "taggedUnions";
public static final String NG_VERSION = "ngVersion";
public static final String PROVIDED_IN_ROOT = "providedInRoot";
@@ -59,7 +56,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
protected String ngVersion = "8.0.0";
protected String npmRepository = null;
private boolean useSingleRequestParameter = false;
protected String serviceSuffix = "Service";
protected String serviceFileSuffix = ".service";
protected String modelSuffix = "";
@@ -88,9 +84,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
this.cliOptions.add(CliOption.newBoolean(WITH_INTERFACES,
"Setting this property to true will generate interfaces next to the default class implementations.",
false));
this.cliOptions.add(CliOption.newBoolean(USE_SINGLE_REQUEST_PARAMETER,
"Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.",
false));
this.cliOptions.add(CliOption.newBoolean(TAGGED_UNIONS,
"Use discriminators to create tagged unions instead of extending interfaces.",
this.taggedUnions));
@@ -168,11 +161,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
apiTemplateFiles.put("apiInterface.mustache", "Interface.ts");
}
}
if (additionalProperties.containsKey(USE_SINGLE_REQUEST_PARAMETER)) {
this.setUseSingleRequestParameter(convertPropertyToBoolean(USE_SINGLE_REQUEST_PARAMETER));
}
writePropertyBack(USE_SINGLE_REQUEST_PARAMETER, getUseSingleRequestParameter());
if (additionalProperties.containsKey(TAGGED_UNIONS)) {
taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString());
@@ -342,6 +330,16 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
if (isLanguagePrimitive(openAPIType) || isLanguageGenericType(openAPIType)) {
return openAPIType;
}
applyLocalTypeMapping(openAPIType);
return openAPIType;
}
private String applyLocalTypeMapping(String type) {
if (typeMapping.containsKey(type)) {
type = typeMapping.get(type);
@@ -349,6 +347,19 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
return type;
}
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType : languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}
return false;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
@@ -556,26 +567,17 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
@Override
public String toApiImport(String name) {
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
return apiPackage() + "/" + toApiFilename(name);
}
@Override
public String toModelFilename(String name) {
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
return DEFAULT_IMPORT_PREFIX + this.convertUsingFileNamingConvention(this.sanitizeName(name)) + modelFileSuffix;
return this.convertUsingFileNamingConvention(this.sanitizeName(name)) + modelFileSuffix;
}
@Override
public String toModelImport(String name) {
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
return modelPackage() + "/" + toModelFilename(name).substring(DEFAULT_IMPORT_PREFIX.length());
return modelPackage() + "/" + toModelFilename(name);
}
public String getNpmRepository() {
@@ -586,14 +588,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
this.npmRepository = npmRepository;
}
private boolean getUseSingleRequestParameter() {
return useSingleRequestParameter;
}
private void setUseSingleRequestParameter(boolean useSingleRequestParameter) {
this.useSingleRequestParameter = useSingleRequestParameter;
}
private String getApiFilenameFromClassname(String classname) {
String name = classname.substring(0, classname.length() - serviceSuffix.length());
return toApiFilename(name);

View File

@@ -107,6 +107,7 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege
supportingFiles.add(new SupportingFile("baseApi.mustache", "", "base.ts"));
supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));
supportingFiles.add(new SupportingFile("custom.d.mustache", "", "custom.d.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));

View File

@@ -0,0 +1,779 @@
/*
* 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
*
* http://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.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.Map.Entry;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptClientCodegen.class);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static final String UNDEFINED_VALUE = "undefined";
private static final String FRAMEWORK_SWITCH = "framework";
private static final String FRAMEWORK_SWITCH_DESC = "Specify the framework which should be used in the client code.";
private static final String[] FRAMEWORKS = { "fetch-api", "jquery" };
private static final String PLATFORM_SWITCH = "platform";
private static final String PLATFORM_SWITCH_DESC = "Specifies the platform the code should run on. The default is 'node' for the 'request' framework and 'browser' otherwise.";
private static final String[] PLATFORMS = { "browser", "node" };
private static final String FILE_CONTENT_DATA_TYPE= "fileContentDataType";
private static final String FILE_CONTENT_DATA_TYPE_DESC = "Specifies the type to use for the content of a file - i.e. Blob (Browser) / Buffer (node)";
private static final String USE_RXJS_SWITCH = "useRxJS";
private static final String USE_RXJS_SWITCH_DESC = "Enable this to internally use rxjs observables. If disabled, a stub is used instead. This is required for the 'angular' framework.";
private final Map<String, String> frameworkToHttpLibMap;
protected String modelPropertyNaming = "camelCase";
protected HashSet<String> languageGenericTypes;
public TypeScriptClientCodegen() {
super();
this.frameworkToHttpLibMap = new HashMap<>();
this.frameworkToHttpLibMap.put("fetch-api", "isomorphic-fetch");
this.frameworkToHttpLibMap.put("jquery", "jquery");
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
outputFolder = "generated-code/typescript";
embeddedTemplateDir = templateDir = "typescript";
supportsInheritance = true;
// NOTE: TypeScript uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons.
reservedWords.addAll(Arrays.asList(
// local variable names used in API methods (endpoints)
"varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
"requestOptions",
// Typescript reserved words
"abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"));
languageSpecificPrimitives = new HashSet<>(Arrays.asList(
"string",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object",
"Array",
"Date",
"number",
"any",
"File",
"Error",
"Map"
));
languageGenericTypes = new HashSet<String>(Arrays.asList(
"Array"
));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
typeMapping.put("Array", "Array");
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("int", "number");
typeMapping.put("float", "number");
typeMapping.put("number", "number");
typeMapping.put("long", "number");
typeMapping.put("short", "number");
typeMapping.put("char", "string");
typeMapping.put("double", "number");
typeMapping.put("object", "any");
typeMapping.put("integer", "number");
typeMapping.put("Map", "any");
typeMapping.put("date", "string");
typeMapping.put("DateTime", "Date");
typeMapping.put("binary", "any");
// TODO: allow other types for file e.g. Blob
typeMapping.put("File", "any");
typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
typeMapping.put("Error", "Error");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false"));
cliOptions.add(new CliOption(TypeScriptClientCodegen.FILE_CONTENT_DATA_TYPE, TypeScriptClientCodegen.FILE_CONTENT_DATA_TYPE_DESC).defaultValue("Buffer"));
cliOptions.add(new CliOption(TypeScriptClientCodegen.USE_RXJS_SWITCH, TypeScriptClientCodegen.USE_RXJS_SWITCH_DESC).defaultValue("false"));
CliOption frameworkOption = new CliOption(TypeScriptClientCodegen.FRAMEWORK_SWITCH, TypeScriptClientCodegen.FRAMEWORK_SWITCH_DESC);
for (String option: TypeScriptClientCodegen.FRAMEWORKS) {
// TODO: improve description?
frameworkOption.addEnum(option, option);
}
frameworkOption.defaultValue(FRAMEWORKS[0]);
cliOptions.add(new CliOption(TypeScriptClientCodegen.PLATFORM_SWITCH, TypeScriptClientCodegen.PLATFORM_SWITCH_DESC));
CliOption platformOption = new CliOption(TypeScriptClientCodegen.PLATFORM_SWITCH, TypeScriptClientCodegen.PLATFORM_SWITCH_DESC);
for (String option: TypeScriptClientCodegen.PLATFORMS) {
// TODO: improve description?
platformOption.addEnum(option, option);
}
platformOption.defaultValue(PLATFORMS[0]);
cliOptions.add(frameworkOption);
// TODO: gen package.json?
//Documentation
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile(".gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
// Util
supportingFiles.add(new SupportingFile("util.mustache", "", "util.ts"));
supportingFiles.add(new SupportingFile("api/exception.mustache", "apis", "exception.ts"));
// http
supportingFiles.add(new SupportingFile("http" + File.separator + "http.mustache", "http", "http.ts"));
supportingFiles.add(new SupportingFile("http/servers.mustache", "servers.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));
supportingFiles.add(new SupportingFile("auth" + File.separator + "auth.mustache", "auth", "auth.ts"));
supportingFiles.add(new SupportingFile("model/models_all.mustache", "models", "all.ts"));
// TODO: add supporting files depending on cli parameter e.g. fetch vs angular
supportingFiles.add(new SupportingFile("generators/types/PromiseAPI.mustache", "types", "PromiseAPI.ts"));
supportingFiles.add(new SupportingFile("generators/types/ObservableAPI.mustache", "types", "ObservableAPI.ts"));
// models
// TODO: properly set model and api packages
this.setModelPackage("");
supportingFiles.add(new SupportingFile("model/ObjectSerializer.mustache", "models", "ObjectSerializer.ts"));
modelTemplateFiles.put("model/model.mustache", ".ts");
// api
this.setApiPackage("");
supportingFiles.add(new SupportingFile("api/middleware.mustache", "", "middleware.ts"));
this.supportingFiles.add(new SupportingFile("api/baseapi.mustache", "apis", "baseapi.ts"));
this.apiTemplateFiles.put("api/api.mustache", ".ts");
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
final Object propFramework = additionalProperties.get(FRAMEWORK_SWITCH);
Map<String, Boolean> frameworks = new HashMap<>();
for (String framework: FRAMEWORKS) {
frameworks.put(framework, framework.equals(propFramework));
}
objs.put("framework", propFramework);
objs.put("frameworks", frameworks);
objs.put("fileContentDataType", additionalProperties.get(FILE_CONTENT_DATA_TYPE));
return objs;
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> operations, List<Object> models) {
// Add additional filename information for model imports in the apis
List<Map<String, Object>> imports = (List<Map<String, Object>>) operations.get("imports");
for (Map<String, Object> im : imports) {
im.put("filename", ((String) im.get("import")).replace('.', '/'));
im.put("classname", getModelnameFromModelFilename(im.get("import").toString()));
}
@SuppressWarnings("unchecked")
Map<String, Object> operationsMap = (Map<String, Object>) operations.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operationsMap.get("operation");
for (CodegenOperation operation: operationList) {
List<CodegenResponse> responses = operation.responses;
operation.returnType = this.getReturnType(responses);
}
return operations;
}
private String getReturnType(List<CodegenResponse> responses) {
StringBuilder returnType = new StringBuilder();
boolean firstReturnType = true;
boolean atLeastOneSuccess = false;
boolean addVoid = false;
System.out.println(responses);
for (CodegenResponse response: responses) {
// TODO: we should probably catch an exception here
if (response.isSuccessCode) {
if (response.dataType != null) {
if (!firstReturnType) {
returnType.append(" | ");
}
returnType.append(response.dataType);
firstReturnType = false;
atLeastOneSuccess = true;
} else {
addVoid = true;
}
}
}
if (!atLeastOneSuccess) {
return null;
} else if (addVoid) {
returnType.append(" | void");
}
System.out.println("Return Type: " + returnType);
return returnType.toString();
}
private String getModelnameFromModelFilename(String filename) {
String name = filename.substring((modelPackage() + File.separator).length());
return camelize(name);
}
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
if ("_".equals(name)) {
name = "_u";
}
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
name = getNameUsingModelPropertyNaming(name);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
if (languageSpecificPrimitives.contains(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName);
return modelName;
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
protected String getParameterDataType(Parameter parameter, Schema p) {
// handle enums of various data types
Schema inner;
if (ModelUtils.isArraySchema(p)) {
ArraySchema mp1 = (ArraySchema) p;
inner = mp1.getItems();
return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
} else if (ModelUtils.isStringSchema(p)) {
// Handle string enums
if (p.getEnum() != null) {
return enumValuesToEnumTypeUnion(p.getEnum(), "string");
}
} else if (ModelUtils.isIntegerSchema(p)) {
// Handle integer enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
} else if (ModelUtils.isNumberSchema(p)) {
// Handle double enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
}
/* TODO revise the logic below
else if (ModelUtils.isDateSchema(p)) {
// Handle date enums
DateSchema sp = (DateSchema) p;
if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
}
} else if (ModelUtils.isDateTimeSchema(p)) {
// Handle datetime enums
DateTimeSchema sp = (DateTimeSchema) p;
if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
}
}*/
return this.getTypeDeclaration(p);
}
/**
* Converts a list of strings to a literal union for representing enum values as a type.
* Example output: 'available' | 'pending' | 'sold'
*
* @param values list of allowed enum values
* @param dataType either "string" or "number"
* @return a literal union for representing enum values as a type
*/
protected String enumValuesToEnumTypeUnion(List<String> values, String dataType) {
StringBuilder b = new StringBuilder();
boolean isFirst = true;
for (String value : values) {
if (!isFirst) {
b.append(" | ");
}
b.append(toEnumValue(value.toString(), dataType));
isFirst = false;
}
return b.toString();
}
/**
* Converts a list of numbers to a literal union for representing enum values as a type.
* Example output: 3 | 9 | 55
*
* @param values a list of numbers
* @return a literal union for representing enum values as a type
*/
protected String numericEnumValuesToEnumTypeUnion(List<Number> values) {
List<String> stringValues = new ArrayList<>();
for (Number value : values) {
stringValues.add(value.toString());
}
return enumValuesToEnumTypeUnion(stringValues, "number");
}
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isDateSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isDateTimeSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'";
}
return UNDEFINED_VALUE;
} else {
return UNDEFINED_VALUE;
}
}
@Override
protected boolean isReservedWord(String word) {
// NOTE: This differs from super's implementation in that TypeScript does _not_ want case insensitive matching.
return reservedWords.contains(word);
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type))
return type;
} else
type = openAPIType;
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
// append _ at the beginning, e.g. _return
if (isReservedWord(operationId)) {
return escapeReservedWord(camelize(sanitizeName(operationId), true));
}
return camelize(sanitizeName(operationId), true);
}
public void setModelPropertyNaming(String naming) {
if ("original".equals(naming) || "camelCase".equals(naming) ||
"PascalCase".equals(naming) || "snake_case".equals(naming)) {
this.modelPropertyNaming = naming;
} else {
throw new IllegalArgumentException("Invalid model property naming '" +
naming + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
public String getModelPropertyNaming() {
return this.modelPropertyNaming;
}
public String getNameUsingModelPropertyNaming(String name) {
switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) {
case original:
return name;
case camelCase:
return camelize(name, true);
case PascalCase:
return camelize(name);
case snake_case:
return underscore(name);
default:
throw new IllegalArgumentException("Invalid model property naming '" +
name + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
@Override
public String toEnumValue(String value, String datatype) {
if ("number".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "Empty";
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(getSymbolName(name));
}
// number
if ("number".equals(datatype)) {
String varName = "NUMBER_" + name;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(name);
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
// camelize the enum variable name
// ref: https://basarat.gitbooks.io/typescript/content/docs/enums.html
enumName = camelize(enumName);
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = toModelName(property.name) + "Enum";
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
List<Map<String, Object>> models = (List<Map<String, Object>>) postProcessModelsEnum(objs).get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.imports = new TreeSet(cm.imports);
// name enum with model name, e.g. StatusEnum => Pet.StatusEnum
for (CodegenProperty var : cm.vars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName);
}
}
if (cm.parent != null) {
for (CodegenProperty var : cm.allVars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum
.replace(var.enumName, cm.classname + var.enumName);
}
}
}
}
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
// Add additional filename information for imports
mo.put("tsImports", toTsImports(cm, cm.imports));
}
return objs;
}
private List<Map<String, String>> toTsImports(CodegenModel cm, Set<String> imports) {
List<Map<String, String>> tsImports = new ArrayList<>();
for (String im : imports) {
if (!im.equals(cm.classname)) {
HashMap<String, String> tsImport = new HashMap<>();
// TVG: This is used as class name in the import statements of the model file
tsImport.put("classname", im);
tsImport.put("filename", toModelFilename(im));
tsImports.add(tsImport);
}
}
return tsImports;
}
@Override
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessAllModels(objs);
for (Map.Entry<String, Object> entry : result.entrySet()) {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
if (cm.discriminator != null && cm.children != null) {
for (CodegenModel child : cm.children) {
this.setDiscriminatorValue(child, cm.discriminator.getPropertyName(), this.getDiscriminatorValue(child));
}
}
}
}
return result;
}
private void setDiscriminatorValue(CodegenModel model, String baseName, String value) {
for (CodegenProperty prop : model.allVars) {
if (prop.baseName.equals(baseName)) {
prop.discriminatorValue = value;
}
}
if (model.children != null) {
final boolean newDiscriminator = model.discriminator != null;
for (CodegenModel child : model.children) {
this.setDiscriminatorValue(child, baseName, newDiscriminator ? value : this.getDiscriminatorValue(child));
}
}
}
private String getDiscriminatorValue(CodegenModel model) {
return model.vendorExtensions.containsKey(X_DISCRIMINATOR_TYPE) ?
(String) model.vendorExtensions.get(X_DISCRIMINATOR_TYPE) : model.classname;
}
@Override
public String escapeQuotationMark(String input) {
// remove ', " to avoid code injection
return input.replace("\"", "").replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String getName() {
return "typescript";
}
@Override
public String getHelp() {
return "Generates a TypeScript client library using Fetch API (beta).";
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
}
convertPropertyToBooleanAndWriteBack(CodegenConstants.SUPPORTS_ES6);
// change package names
apiPackage = this.apiPackage + ".apis";
modelPackage = this.modelPackage + ".models";
testPackage = this.testPackage + ".tests";
additionalProperties.putIfAbsent(FRAMEWORK_SWITCH, FRAMEWORKS[0]);
supportingFiles.add(new SupportingFile(
"generators" + File.separator + additionalProperties.get(FRAMEWORK_SWITCH) + ".mustache",
"index.ts"
));
String httpLibName = this.getHttpLibForFramework(additionalProperties.get(FRAMEWORK_SWITCH).toString());
supportingFiles.add(new SupportingFile(
"http" + File.separator + httpLibName + ".mustache",
"http", httpLibName + ".ts"
));
Object propPlatform = additionalProperties.get(PLATFORM_SWITCH);
if (propPlatform == null) {
propPlatform = "browser";
additionalProperties.put("platform", propPlatform);
}
Map<String, Boolean> platforms = new HashMap<>();
for (String platform: PLATFORMS) {
platforms.put(platform, platform.equals(propPlatform));
}
additionalProperties.put("platforms", platforms);
additionalProperties.putIfAbsent(FILE_CONTENT_DATA_TYPE, propPlatform.equals("node") ? "Buffer" : "Blob");
final boolean useRxJS = convertPropertyToBooleanAndWriteBack(USE_RXJS_SWITCH);
if (!useRxJS) {
supportingFiles.add(new SupportingFile("rxjsStub.mustache", "", "rxjsStub.ts"));
}
}
private String getHttpLibForFramework(String object) {
return this.frameworkToHttpLibMap.get(object);
}
@Override
public String getTypeDeclaration(Schema p) {
Schema inner;
if (ModelUtils.isArraySchema(p)) {
inner = ((ArraySchema) p).getItems();
return this.getSchemaType(p) + "<" + this.getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
} else if (ModelUtils.isFileSchema(p)) {
// TODO: Change type declaration
return "HttpFile";
} else if (ModelUtils.isBinarySchema(p)) {
return "any";
} else {
return super.getTypeDeclaration(p);
}
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
codegenModel.additionalPropertiesType = getTypeDeclaration((Schema) schema.getAdditionalProperties());
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
}

View File

@@ -54,6 +54,8 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
outputFolder = "generated-code/typescript-fetch";
embeddedTemplateDir = templateDir = "typescript-fetch";
this.apiPackage = "src" + File.separator +"apis";
this.modelPackage = "src" + File.separator + "models";
this.apiTemplateFiles.put("apis.mustache", ".ts");
this.modelTemplateFiles.put("models.mustache", ".ts");
this.addExtraReservedWords();
@@ -96,17 +98,10 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
super.processOpts();
additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming().equals("original"));
additionalProperties.put("modelPropertyNaming", getModelPropertyNaming());
String sourceDir = "";
if (additionalProperties.containsKey(NPM_NAME)) {
sourceDir = "src" + File.separator;
}
this.apiPackage = sourceDir + "apis";
this.modelPackage = sourceDir + "models";
supportingFiles.add(new SupportingFile("index.mustache", sourceDir, "index.ts"));
supportingFiles.add(new SupportingFile("runtime.mustache", sourceDir, "runtime.ts"));
supportingFiles.add(new SupportingFile("index.mustache", "src", "index.ts"));
supportingFiles.add(new SupportingFile("runtime.mustache", "src", "runtime.ts"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
if (additionalProperties.containsKey(USE_SINGLE_REQUEST_PARAMETER)) {
this.setUseSingleRequestParameter(convertPropertyToBoolean(USE_SINGLE_REQUEST_PARAMETER));
@@ -216,9 +211,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
//Files for building our lib
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile("npmignore.mustache", "", ".npmignore"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
}
@Override

View File

@@ -1,104 +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
*
* http://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.templating.mustache;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template.Fragment;
/**
* Splits long fragments into smaller strings and uses a StringBuilder to merge
* them back.
*
* Register:
*
* <pre>
* additionalProperties.put("lambdaSplitString", new SplitStringLambda());
* </pre>
*
* Use:
*
* <pre>
* {{#lambdaSplitString}}{{summary}}{{/lambdaSplitString}}
* </pre>
*/
public class SplitStringLambda implements Mustache.Lambda {
private static final int DEFAULT_MAX_LENGTH = 65535;
private static final String SPLIT_INIT = "new StringBuilder(%d)";
private static final String SPLIT_PART = ".append(\"%s\")";
private static final String SPLIT_SUFFIX = ".toString()";
private final int maxLength;
public SplitStringLambda() {
this(DEFAULT_MAX_LENGTH);
}
public SplitStringLambda(int maxLength) {
this.maxLength = maxLength;
}
@Override
public void execute(Fragment fragment, Writer writer) throws IOException {
String input = fragment.execute();
int inputLength = input.length();
StringBuilder builder = new StringBuilder();
if (inputLength > maxLength) {
// Initialize a StringBuilder
builder.append(String.format(Locale.ROOT, SPLIT_INIT, inputLength));
int currentPosition = 0;
int currentStringLength = 0;
char currentLastChar = '\\';
// Split input into parts of at most maxLength and not ending with an escape character
// Append each part to the StringBuilder
while (currentPosition + maxLength < input.length()) {
currentStringLength = maxLength;
currentLastChar = input.charAt(currentPosition + currentStringLength - 1);
if (currentLastChar == '\\') {
--currentStringLength;
}
builder.append(String.format(Locale.ROOT, SPLIT_PART, input.substring(currentPosition, currentPosition + currentStringLength)));
currentPosition += currentStringLength;
}
// Append last part if necessary
if (currentPosition < input.length()) {
builder.append(String.format(Locale.ROOT, SPLIT_PART, input.substring(currentPosition)));
}
// Close the builder and merge everything back to a string
builder.append(SPLIT_SUFFIX);
} else {
builder.append(String.format(Locale.ROOT, "\"%s\"", input));
}
writer.write(builder.toString());
}
}

View File

@@ -1,49 +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
*
* http://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.templating.mustache;
import java.io.IOException;
import java.io.Writer;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template.Fragment;
/**
* Replaces duplicate whitespace characters in a fragment with single space.
*
* Register:
* <pre>
* additionalProperties.put("lambdaTrimWhitespace", new TrimWhitespaceLambda());
* </pre>
*
* Use:
* <pre>
* {{#lambdaTrimWhitespace}}{{name}}{{/lambdaTrimWhitespace}}
* </pre>
*/
public class TrimWhitespaceLambda implements Mustache.Lambda {
private static final String SINGLE_SPACE = " ";
private static final String WHITESPACE_REGEX = "\\s+";
@Override
public void execute(Fragment fragment, Writer writer) throws IOException {
writer.write(fragment.execute().replaceAll(WHITESPACE_REGEX, SINGLE_SPACE));
}
}

View File

@@ -90,7 +90,6 @@ public class ModelUtils {
* @return schemas a list of used schemas
*/
public static List<String> getAllUsedSchemas(OpenAPI openAPI) {
Map<String, List<String>> childrenMap = getChildrenMap(openAPI);
List<String> allUsedSchemas = new ArrayList<String>();
visitOpenAPI(openAPI, (s, t) -> {
if (s.get$ref() != null) {
@@ -98,13 +97,6 @@ public class ModelUtils {
if (!allUsedSchemas.contains(ref)) {
allUsedSchemas.add(ref);
}
if (childrenMap.containsKey(ref)) {
for (String child : childrenMap.get(ref)) {
if (!allUsedSchemas.contains(child)) {
allUsedSchemas.add(child);
}
}
}
}
});
return allUsedSchemas;
@@ -117,7 +109,6 @@ public class ModelUtils {
* @return schemas a list of unused schemas
*/
public static List<String> getUnusedSchemas(OpenAPI openAPI) {
Map<String, List<String>> childrenMap = getChildrenMap(openAPI);
List<String> unusedSchemas = new ArrayList<String>();
Map<String, Schema> schemas = getSchemas(openAPI);
@@ -125,11 +116,7 @@ public class ModelUtils {
visitOpenAPI(openAPI, (s, t) -> {
if (s.get$ref() != null) {
String ref = getSimpleRef(s.get$ref());
unusedSchemas.remove(ref);
if (childrenMap.containsKey(ref)) {
unusedSchemas.removeAll(childrenMap.get(ref));
}
unusedSchemas.remove(getSimpleRef(s.get$ref()));
}
});
return unusedSchemas;
@@ -872,18 +859,6 @@ public class ModelUtils {
return null;
}
public static Map<String, List<String>> getChildrenMap(OpenAPI openAPI) {
Map<String, Schema> allSchemas = getSchemas(openAPI);
Map<String, List<Entry<String, Schema>>> groupedByParent = allSchemas.entrySet().stream()
.filter(entry -> isComposedSchema(entry.getValue()))
.collect(Collectors.groupingBy(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas)));
return groupedByParent.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue().stream().map(e -> e.getKey()).collect(Collectors.toList())));
}
/**
* Get the interfaces from the schema (composed)
*

View File

@@ -73,14 +73,11 @@ set(HDRS "")
## This section shows how to use the above compiled libary to compile the source files
## set source files
#set(SRCS
{{#apiInfo}}
{{#apis}}
{{#operations}}
# unit-tests/manual-{{classname}}.c
{{/operations}}
{{/apis}}
{{/apiInfo}}
#)
# unit-tests/manual-PetAPI.c
# unit-tests/manual-StoreAPI.c
# unit-tests/manual-UserAPI.c
# unit-tests/manual-order.c
# unit-tests/manual-user.c)
##set header files
#set(HDRS

View File

@@ -14,7 +14,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
## Installation
You'll need the `curl 7.58.0` package in order to build the API. To have code formatted nicely, you also need to have uncrustify version 0.67 or later.
You'll need the `curl 7.58.0` package in order to build the API. To have code formatted nicely you also need to have uncrustify version 0.67.
# Prerequisites
@@ -40,11 +40,11 @@ sudo make install
```
## Compile the sample:
This will compile the generated code and create a library in the build folder which has to be linked to the codes where API will be used.
This will compile the generated code and create a library in build folder which has to be linked to the codes where API will be used.
```bash
mkdir build
cd build
// To install library to specific location, use following commands
// To install library to specific location use following command
cmake -DCMAKE_INSTALL_PREFIX=/pathtolocaiton ..
// for normal install use following command
cmake ..
@@ -58,11 +58,11 @@ To compile main.c(considering the file is present in build folder) use following
-L - locaiton of the library(not required if cmake with normal installation is performed)
-l library name
```bash
gcc main.c -L. -l{{projectName}} -o main
gcc main.c -L. -lpetstore -o main
```
Once compiled, you can run it with ``` ./main ```
once compile, you can run it with ``` ./main ```
Note: You don't need to specify includes for models and include folder seperately as they are path linked. You just have to import the api.h file in your code, the include linking will work.
Note: You dont need to specify includes for models and include folder seperately as they are path linked. You just have to import the api.h file in your code, the include linking will work.
## Author

View File

@@ -28,7 +28,6 @@ repositories {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.10"
jackson_databind_version = "2.9.10.1"
}
dependencies {
@@ -36,7 +35,7 @@ dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
compile 'io.github.http-builder-ng:http-builder-ng-core:1.0.3'

View File

@@ -137,7 +137,7 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.10"
jackson_databind_version = "2.9.10.1"
jackson_databind_version = "2.9.10"
jackson_databind_nullable_version = "0.2.0"
jersey_version = "1.19.4"
jodatime_version = "2.9.9"

View File

@@ -121,7 +121,7 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.10"
jackson_databind_version = "2.9.10.1"
jackson_databind_version = "2.9.10"
jackson_databind_nullable_version = "0.2.0"
{{#threetenbp}}
jackson_threetenbp_version = "2.9.10"

View File

@@ -16,7 +16,7 @@ lazy val root = (project in file(".")).
"io.github.openfeign.form" % "feign-form" % "2.1.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10.1" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}" % "2.9.10" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",

View File

@@ -316,7 +316,7 @@
<feign-form-version>2.1.0</feign-form-version>
<jackson-version>2.9.10</jackson-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
<jackson-databind-version>2.9.10.1</jackson-databind-version>
<jackson-databind-version>2.9.10</jackson-databind-version>
{{#threetenbp}}
<jackson-threetenbp-version>2.9.10</jackson-threetenbp-version>
{{/threetenbp}}

View File

@@ -121,7 +121,7 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.10"
jackson_databind_version = "2.9.10.1"
jackson_databind_version = "2.9.10"
jackson_databind_nullable_version = "0.2.0"
google_api_client_version = "1.23.0"
jersey_common_version = "2.25.1"

View File

@@ -14,7 +14,7 @@ lazy val root = (project in file(".")).
"org.glassfish.jersey.core" % "jersey-common" % "2.25.1",
"com.fasterxml.jackson.core" % "jackson-core" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10.1" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10" % "compile",
{{#withXml}}
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.9.10" % "compile",
{{/withXml}}

View File

@@ -307,7 +307,7 @@
<google-api-client-version>1.30.2</google-api-client-version>
<jersey-common-version>2.25.1</jersey-common-version>
<jackson-version>2.9.10</jackson-version>
<jackson-databind-version>2.9.10.1</jackson-databind-version>
<jackson-databind-version>2.9.10</jackson-databind-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
{{#joda}}
<jodatime-version>2.9.9</jodatime-version>

View File

@@ -120,7 +120,7 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.10"
jackson_databind_version = "2.9.10.1"
jackson_databind_version = "2.9.10"
jackson_databind_nullable_version = "0.2.0"
{{#supportJava6}}
jersey_version = "2.6"

View File

@@ -15,7 +15,7 @@ lazy val root = (project in file(".")).
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.25.1"{{/supportJava6}},
"com.fasterxml.jackson.core" % "jackson-core" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10.1" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10" % "compile",
{{#joda}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile",
{{/joda}}

View File

@@ -361,7 +361,7 @@
<commons_lang3_version>3.6</commons_lang3_version>
{{/supportJava6}}
<jackson-version>2.9.10</jackson-version>
<jackson-databind-version>2.9.10.1</jackson-databind-version>
<jackson-databind-version>2.9.10</jackson-databind-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
{{#threetenbp}}
<threetenbp-version>2.9.10</threetenbp-version>

Some files were not shown because too many files have changed in this diff Show More