Compare commits

..

201 Commits

Author SHA1 Message Date
William Cheng
eb627dedfd beta release of dukescript generator 2018-12-07 11:56:47 +08:00
William Cheng
774013c7e1 Better OpenAPI spec v3 support: allOf, anyOf, oneOf (#1360)
* add oneOf support to Ruby

* add anyOf support to ruby client

* add discriminator support to ruby client

* fix typo

* update samples, fix NPE

* better format in ruby generator

* fix test cases, disable mapping test

* fix update script, update samples

* add test, fix mapping

* update exit code

* reenabled discriminator test

* remove duplicated properties

* add test for duplicated properties

* update samples, add new spec

* fix ruby test cases

* fix hasMore after removing duplicates

* refactor method, comment out haskell client test

* fix hasMore and update samples

* fix parent detection

* fix discriminator check

* [haskell-http-client] need to use {{vars}}{{required}} instead of {{requiredVars}}

* remove deprecated methods in default codegen (#1031)

* regenerate samples

* remove commented code
2018-12-07 00:30:20 +08:00
Erik Timmers
c0634ac213 [elm] Enable setting Http request trackers (#1609) 2018-12-06 23:41:44 +08:00
William Cheng
92d60b684a update samples 2018-12-06 18:58:21 +08:00
Jaumard
d40cbf9dbd add default timeout to calls (#1596)
add properties to send or not null values
update deps
2018-12-06 18:34:01 +08:00
William Cheng
d57009d14d Merge branch 'master' of https://github.com/OpenAPITools/openapi-generator 2018-12-06 17:22:19 +08:00
Atsushi Hanaoka
ced6e0502e [typescript] Avoid strictNullChecks errors for apiKeys (#1611)
* [typescript] Avoid strictNullChecks errors for apiKeys

fix #1607

* Run ./bin/{LANG}-petstore.sh

- ./bin/typescript-angular-petstore-all.sh
- ./bin/typescript-inversify-petstore.sh

* Run ./bin/security/{LANG}-petstore.sh

- ./bin/security/typescript-angular.sh
- ./bin/security/typescript-angular2.sh
- ./bin/security/typescript-inversify.sh

* [typescript] Fix parameter name sanitization

* Fix invalid consumes of petstore-security-test.yaml

* Run ./bin/security/typescript-*.sh
2018-12-06 17:10:45 +08:00
William Cheng
314b4cc54f remove deprecated methods in default codegen (#1031) 2018-12-06 16:17:32 +08:00
William Cheng
21b2b20c2d Merge remote-tracking branch 'origin/4.0.x' 2018-12-06 12:21:14 +08:00
Prateek Malhotra
1e023f3b6e [Typescript][Fetch] Fix bugs with new typescript-fetch generator (#1545)
* [Typescript][Fetch] Always initialize queryParameters

* [Typescript][Fetch] Resolve date and date-time formats to parameter type Date

* [Typescript][Fetch] Update models template

- Add `readonly` modifier to readOnly parameters.
- Omit readOnly parameters from requests when serializing models
- Use allVars in models template when serializing/deserializing requests

* [Typescript][Fetch] Omit time component when parameter format: date

* [Typescript][Fetch] Add moduleResolution: node option to tsconfig.json

* [Typescript][Fetch] Added non-model enums
2018-12-06 12:20:34 +08:00
Hemant Zope
df19c13347 [C] Resolve some issues from #1473 (#1497)
* change folder structure for external and added list as primitive type

* modified gitignore for C generator

* change include statement as per directory structure

* added projectname variable for using in cmakelists

* modified cmakefile:compile files irrespective of testfiles and add support for make install

* updated readme with how to compile and how to use

* CMakeLists change curl to 7.58.0

* fix indentation

* add remove as reserved word
2018-12-06 11:39:30 +08:00
William Cheng
32d228c33a Add GraphQL Server owner (renepardon) to the README (#1620) 2018-12-06 10:37:46 +08:00
William Cheng
fcd37a6006 re-enable haskell client test (#1621) 2018-12-06 10:37:25 +08:00
William Cheng
4be605bcb7 GraphQL Server (#1603)
* Add GraphQL express/apollo server generator

* add basic resolvers; adjust parameters/input types

* small adjustments and improvements

* adjust logger config for GraphQL generators

* remove MaxPermSize form bash script as it will be removed from later Java versions; add isNullable utility helper method; Adjust TODOs for graphql implementation

* re-created samples for graphql config and server generators

* re-added templates for graphql config generator

* add graphql-config-petstore bash script

* add isNullable utility method

* fix javadoc issues

* adjust licence headers

* rename Generator to Codegen for GraphQL classes

* renaming, minor enhancement to graphql generator

* add graphql server samples

* add windows batch files, rename directory
2018-12-05 18:20:53 +08:00
William Cheng
01ac429954 fix TS version check (#1616) 2018-12-05 18:06:55 +08:00
Philipp Kainz
10ea00066a [typescript-angular] Angular 7 compatibility of dependencies and package generator (#1613)
* added Angular v7 compatibility version support

* fix logic error

* updated petstore samples

* fixed failing tests and added Angular 7 client test app
2018-12-05 15:15:51 +08:00
Mark Thebridge
4930f75dc7 Generic JSON body support in rust-server (#1523)
* Ensure that generic JSON bodies are correctly autogenerated

Generates valid Rust for an arbitrary JSON response body of type `object` with no other schema.
2018-12-04 16:51:59 +00:00
William Cheng
8795bff35e Merge remote-tracking branch 'origin/4.0.x' 2018-12-04 23:26:52 +08:00
Fabrizio Ferrai
6976a8c775 Upgrade haskell-servant generator to latest LTS (#1469)
* [Haskell Servant] Upgrade to lts-12

- Upgrade Servant to the latest version
- Add Maybe for optional values
- Add UUID, UTCTime and Day types
- Fix the URL configuration so that it has one param with all data
- Add Data and ToSchema instances to models
- Switch to TLS http manager so it can connect to https urls
- Add nicer API to call the endpoints
- Add Nix support

* [Haskell Servant] Upgrade Petstore

* [Haskell Servant] Delete old swagger-petstore samples

* [Haskell Servant] Use generics for ToForm and FromForm instances

* [Haskell Servant] Generate ToSchema instance only if it's safe to do
2018-12-04 19:03:08 +08:00
Rubén Martínez
110d057384 [csharp] Fixed issue #1524: useDateTimeOffset not working in openapi generator 3.3.3 (#1544)
* Run ./bin/utils/ensure-up-to-date to re-generate samples run in the CI.

* Fixed issue #1524 that caused the `useDateTimeOffset` additional property for the `csharp` generator not to work.
2018-12-04 18:59:15 +08:00
Erik Timmers
d75392e056 [elm] Enable setting base path for each request (#1538) 2018-12-04 18:36:55 +08:00
Juan Eugenio Abadie
e84c59f4cc [cpp rest-sdk] Add status code to response handler (#1541)
* Add status code parameter to the response handler

* Update PetStore
2018-12-04 18:35:39 +08:00
Kiran-Sivakumar
0a33ad465f [Java][okhttp-gson] Fix bug when performing OAuth token retry (#1576)
* Fix access token retry bug

* Update petstore samples

* Remove newline

* Import Pair and List in RetryingOAuth template

* Update petstore samples

* Update petstore samples
2018-12-04 18:33:10 +08:00
Denis Korenevskiy
8ee1553654 Replace <tt> tags with <code> to make new jacadoc work. (#1585)
Replace <tt> tags with <code> to make new javadoc work.
2018-12-04 18:16:23 +08:00
Christophe Bornet
001f89f1d9 Add tests to online generator (#1591) 2018-12-04 18:14:50 +08:00
William Cheng
cd61442387 Improve checkout script on NPMJS wrapper (#1595)
* improve checkout on npmjs wrapper

* update readme
2018-12-04 11:14:14 +08:00
Rubén Martínez
e3ab059530 [csharp] Fix #1531 with non-nullable enums on operation parameters not compiling (#1543)
* Run ./bin/utils/ensure-up-to-date to re-generate samples run in the CI.

* Fixed issue #1531. Now in C# operation parameters are post-processed to correctly mark them as enumerations. The api.mustache C# template now marks parameters as nullable when they're non-required enums.

* #1531 Added fix for enum, non-required parameters to the interface of the auto-generated C# Apis.

* Fixed error with the development of ticket #1531, which duplicated nullable question marks for primitive types.
2018-12-03 17:28:08 +08:00
William Cheng
dfa7e616c0 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-12-01 19:18:27 +08:00
William Cheng
2353d71d4b skip stack, dark installation due to travis issue 2018-12-01 01:04:00 +08:00
William Cheng
2f4dc9a049 Prepare 3.3.4 release (#1583)
* update release version

* update doc for 3.3.4 release

* comment out stack installation due to error in travis
2018-12-01 01:00:06 +08:00
Christophe Bornet
54b5093381 Improve online gen resolution of host for the download link (#1580)
Fix #1517
2018-11-30 22:04:17 +08:00
William Cheng
cf2ddb8b8c Fix header parameters display in the documentation (#1579)
* fix header parameters display in html

* fix cwiki header, remove test header parameter
2018-11-30 20:57:52 +08:00
William Cheng
8f8d3547f6 Update JS client dependency (#1578)
* update js dep

* fix missing comma

* remove unused test files in JS

* remove StringBooleanMap.spec.js

* remove StringBooleanMap.spec.js
2018-11-30 18:47:32 +08:00
William Cheng
b226f52d13 Merge remote-tracking branch 'origin' into 4.0.x 2018-11-30 10:16:16 +08:00
William Cheng
eae958f293 Add "b<>com" to the list of companies using OpenAPI Generator (#1573) 2018-11-30 09:22:01 +08:00
sunn
308515bbc1 [cpp-qt5] client response headers and validation of properties for client and server (#1508)
* Add validation of required properties
Add Header extraction for client
* Remove some todos
* Add Test for Store API
Improve some checks for serialization
2018-11-29 11:00:37 +01:00
Michael Ramstein
6930433def [elixir] Typespec - allow null on optional struct-attributes (#1514)
* Typespec - allow null on optional parameters

* Run Petstore for elixir

* considers 'nullable' in model template, fixes 'isRequired'
2018-11-29 15:58:32 +08:00
William Cheng
c537557a91 comment out haskell client build in travis 2018-11-29 11:14:00 +08:00
Akihito Nakano
f7c857cc39 [Spring] Add an option to return success code (#1197)
* Returns status code which defined at Response Object

* Tweak indent

Remove the spacer "{{#async}} ... {{/async}}" "{{^async}} ... {{/async}}"

* Update samples^

* Fix broken indentation

* Update samples

* Revert methodBody.mustache

* Revert "Fix broken indentation"
  * This reverts commit 95b6a00f8b.
* Revert "Tweak indent"
  * This reverts commit ba2cedc897.
* Revert "Returns status code which defined at Response Object"
  * This reverts commit f676a89e23.

* Example contains status code

* Update samples

./bin/spring-all-pestore.sh

* Fix syntax error

* Update samples

* Run bin/utils/ensure-up-to-date

* Make the changes an option `returnSuccessCode`

* Run bin/spring-all-pestore.sh to update samples

* Run ./bin/utils/export_docs_generators.sh
2018-11-29 11:51:25 +09:00
Simas Abramovas
777bf1f3aa Kotlin collection type (#1564)
* Allow specifying type

* Add test

* Update docs

* Don't modify types if the default option is chosen
2018-11-29 10:33:55 +08:00
William Cheng
41185d3c6f Merge branch 'master' of https://github.com/openapitools/openapi-generator 2018-11-28 22:33:54 +08:00
William Cheng
1d4e24b203 comment out c test due to timeout in travis 2018-11-28 22:17:42 +08:00
William Cheng
c63f58f1ef [Elixir] fix ":body" handling (#1504)
* Fix swagger-api/swagger-codegen/issues/8138 swagger-api/swagger-codegen#8138

When JSON payload needs to be in the body (`"in": "body"`), it must not generate a multi-part body, but embed directly in HTTP body.

* update elixir samples

* update elixir client samples

* remove double quote
2018-11-28 21:35:50 +08:00
Kiran-Sivakumar
9df70798b3 [Java][okhttp-gson] Add option to employ builders for API requests (#1341)
* Generate APIs that use the builder pattern

* Add option to use builders for API requests

* Fix template spacing

* Add new sample-generation script and generated samples

* Update docs

* Add new sample-generation script for Windows

* Replace config option with vendor extension

* Remove useBuildersForApiRequests config option

* Remove builders sample-generation scripts

* Replace config option with vendor extension in api_test template

* Remove okhttp-gson-requestBuilders sample

* Rename x-builders-for-api-requests to x-group-parameters

* Add modified api_doc.mustache under okhttp-gson resources

* Add modified README.mustache under okhttp-gson resources

* Update petstore samples

* Fix FakeApiTest.java in petstore samples

* Add whitespace to rerun checks

* Remove whitespace to rerun tests

* Fix FakeApiTest.java in parcelable petstore sample

* Update versions in samples

* Update versions in samples
2018-11-28 17:53:36 +08:00
Akihito Nakano
3efe56752e Improve error message when the spec is not found (#1495)
* Improve error message when spec not found

* Add test yaml

* Fix invalid yaml file path

* Fix typo
2018-11-28 16:50:52 +08:00
rasmusfaber
d8dde6855f Use checksum to decided if input spec has changed. (#1502) 2018-11-28 16:43:00 +08:00
meganemura
ebf67e683c Fix regexp in ruby-client (#1521)
* Fix regexp in ruby-client

* Remove tests for unknown regexp patterns
2018-11-28 16:40:58 +08:00
feihongmeilian
5b4a19849e Upgrade the erlang-server dependency from cowboy1.x to cowboy2.x (#1364)
* Upgrade the erlang-server dependency from cowboy1.x to cowboy2.x

* Update erlang-server sample

* Fix a bug for erlang-server test
2018-11-28 11:50:08 +08:00
William Cheng
9b99b6b6bf better hanlding of string type with different format (#1558) 2018-11-28 11:21:54 +08:00
William Cheng
33016f2790 Update NPM installation instruction (#1556)
* Update NPM installation instruction

* further revise the doc
2018-11-28 00:27:35 +08:00
William Cheng
963173b357 Add link to conference presentation (#1554) 2018-11-27 23:59:23 +08:00
Michael Ramstein
d31fa4f7c4 Typespec: Fixes issue with formated primitivs (#1534) 2018-11-27 21:34:54 +08:00
Michael Ramstein
247bd68880 Decodes list with primitvs (#1536) 2018-11-27 17:00:10 +08:00
Michael Ramstein
4eae430cca [elixir] Fixes BadMapError for header parameters (#1537)
* Adds :headers as expected param mapping

* Gen Petstore
2018-11-27 16:59:16 +08:00
William Cheng
51a3a22928 Add online services to the documentation (#1550)
* update online service

* update readme with online services

* minor wording change

* revise wordings

* add links to linode logo
2018-11-27 15:51:23 +08:00
Erik Timmers
172448fa28 Add support for UUIDs (#1516)
And fix naming for `decode` functions.
2018-11-27 13:47:06 +08:00
William Cheng
46a4ffe64c Skip model generation if it's a top-level map or array (#1296)
* update samples

* remove string boolean map spec

* add logic to skip array alias being generated as model

* fix alias to array

* remove unused ruby files

* remove unused ruby (oas3) files

* unalias response schema

* fix NPE when no model defined

* fix ruby openapi3 script

* update samples

* add global openapi, schemas for unaliasing

* minor code cleanup/refactoring using globalSchemas

* Revert "minor code cleanup/refactoring using globalSchemas"

This reverts commit 20a2bbc6fc.
2018-11-26 22:01:53 +08:00
Yuichi Okada
ce0253892c [PHP client] Fix README.md template for php (#1540)
* Fix README.md template for php

* update php openapi3 samples
2018-11-26 13:41:27 +08:00
Akihito Nakano
34abedeb8a [PHP] Bump minimum required version to PHP7.1 (#1491)
* Bump minimum required version to PHP7.1

ref: http://php.net/supported-versions.php

* Bump phpunit

* Update [api|model]_test.mustache

* Update samples

bin/openapi3/php-petstore.sh

* Update namespace of PHPUnit ("tests" folder)

* `setExpectedException` is deleted in PHPUnit 7.4

* Update namespace of "Assert" class

* The attribute 'name' is required

* Add anotation to exclude the test from risky testcheck

* Update samples (samples/client/petstore/php)

* Apply updates to "test" in openapi2 folder (samples/client/petstore/php)

b3495ecbfe
15e00ae89d
2fc6917d13
0d016c00ed

* Install php7.1

* Switch to php7

* Update samples (security)

bin/security/php-petstore.sh
2018-11-26 08:59:22 +07:00
William Cheng
2146081ffb update elm petstore samples 2018-11-24 19:12:22 +08:00
William Cheng
7db12aa4af Merge remote-tracking branch 'origin' into 4.0.x 2018-11-24 17:48:17 +08:00
William Cheng
bf2932d41c fix array of enum class in JS (#1484) 2018-11-24 17:04:59 +08:00
William Cheng
f8ada391c4 Fix boolean value handling in HTTP request body (#1515)
* fix boolean http body handling

* fix typo in parameter name
2018-11-24 16:42:32 +08:00
Christian Schneider
0ba9278308 #1506 Bump Zone.js to remove warnings when using angular >=6. (#1522)
* 1506 allow zonejs 0.7.x and 0.8.x to support a wider range of angular versions

* #1506 Removed zone.js as peer since it comes with angular itself

* #1506 Removed zone.js as peer since it comes with angular itself
2018-11-24 16:42:09 +08:00
Erik Timmers
e91d6d735d [elm] Add support for nested Lists & Dicts (#1528)
And rename Union Types to Custom Types and Aliases to Records.
2018-11-23 16:03:07 +01:00
Erik Timmers
5f1362daad Update Elm for elm/http 2.0.0 (#1510) 2018-11-23 16:02:55 +01:00
Juan Eugenio Abadie
dd33434064 [cpp rest-sdk] Reponse headers handler (#1511)
* Add support to set a Response headers handler
* Update PetStore
* Fix missing names
* Update PetStore
2018-11-23 11:38:40 +01:00
William Cheng
cf04ba30db Fix the function name starting with numbers (#1513)
* update elixir samples

* fix function name starting with numbers

* add new files
2018-11-23 17:32:51 +08:00
William Cheng
5aa1da7c2e Add utility methods for free-form objects (isFreeFormObject) (#1338)
* add utility methods for models

* add isFreeFormObject tag

* add object mapping for elixir client

* minor fix to free form object check
2018-11-22 18:46:09 +08:00
Jon Schoning
9be5b99266 [haskell-http-client] fix typename generation bug for array params; update deps
- fix build for example-app + tests-integration in Samples (due to change in Category)

  - upgrade stack to 12.18

  - fix typename generation bug for array params
2018-11-20 18:38:07 -06:00
Alwin Garside
792f95eb09 [PHP] Use appDescription in composer.mustache (#1485)
* Use appDescription in composer.mustache

* Update petstore files

* More updated php petstore files

* Yet another updated php petstore file

* Use "{{{appDescription}}}" instead of "{{appDescription}}"
2018-11-20 10:30:14 +09:00
William Cheng
2b58f6737a fix typo in java client docstring (#1494) 2018-11-19 21:14:03 +08:00
William Cheng
363b095721 better warning, default value (#1492) 2018-11-19 20:55:29 +08:00
meganemura
b9949e1a8e Generate a ruby-client sample for OpenAPI 2.0 (#1482)
* Move output directory for bin/openapi3/ruby-client-petstore.sh

$ git mv sample/client/petstore/ruby sample/openapi3/client/petstore/ruby-client

* $ bin/ruby-client-petstore.sh

* Run bin/ruby-client-petstore.sh in bin/utils/ensure-up-to-date
2018-11-19 17:02:19 +08:00
William Cheng
f58bd6d839 fix NPE for scala gatling generator (#1479) 2018-11-19 11:06:16 +08:00
William Cheng
0e693cd9a8 Fix NPE with cpp-restsdk client generator (#1477)
* fix_cpprest_npe

* fix_code_format
2018-11-19 11:05:44 +08:00
William Cheng
65a86eee3b Merge remote-tracking branch 'origin/master' into 4.0.x 2018-11-18 18:54:29 +08:00
PLACE
334415dec2 Typescript fetch fork (#569)
* added my fork from https://github.com/Place1/swagger-codegen-typescript-browser

* ran bin/typescript-fetch-petstore-all.sh

* use FormData.append rather than .set for IE11 compat

* reverted change to licenseInfo.mustache

* reverted some comments

* added package.json and tsconfig.json back to the generator

* added support for blob (application/octet-stream) responses

* models and apis are now in folders

* added support for modelPropertyNaming based on the spec

* bug fix

* updated samples

* Restore pom.xml for typescript project

* Restore samples/client/petstore/typescript-fetch/tests/default/package.json
≈

* added support for response type Date conversion

* updated samples

* Rework pom in "samples.ci"

* Restore "samples/client/petstore/typescript-fetch/tests/default"

* updated configuration class to use property getters to allow clients to implement configuration values as getters

* added {{datatype}}ToJSON functions to handle serialization and naming conversions

* fixed missing import

* fixed compilation error. updated samples

* 1 character change to get CI to run again

* updated samples

* added support for array type request body

* updated tests

* support for optional request bodies

* updated models json converters to handle undefined inputs (to simplify usage in optional contexts like optional request bodies)

* updated samples

* updated tests

* changed to typescript version 2.4

* updated samples

* support for optional properties being null, undefined or omitted

* updated samples

* bug fix

* bug fix

* updated samples

* ran npm install in test project

* patch to get tests running

* added support for retrieving raw response. added support for binary request bodies. added support for blob data type for files/binary.
2018-11-18 13:24:24 +08:00
Ludovic Montel
7f8ff35245 fix #1272 Fix wrong PHP Symfony typehint (#1453)
A model with an array property used to have the wrong PHP typehint in
the setter: the array item object type instead of "array"
2018-11-18 12:38:44 +08:00
Arshad Kazmi
2c418e1b71 Fixed scripts list url in README.md (#1481) 2018-11-18 10:20:32 +09:00
William Cheng
941b3ea015 fix NPE in the C# Nancy generator (#1478) 2018-11-17 10:11:14 -05:00
William Cheng
c656194f22 Add C template creator to project's README (#1476) 2018-11-17 18:42:40 +08:00
Steven Masala
5b57eae5de add TUI InfoTec GmbH as company (#1472) 2018-11-17 11:38:13 +08:00
William Cheng
edc05df774 Add C client generator (#516)
* add c generator (1st commit)

* udpate c model template

* more fixes

* Add string replace function for C generator (#908)

* Add string replace function for C generator

* Fixed replacement for variable only

* Fixed problem for different datatypes of paramName

* store return value of modified path

* set str_replace variable to be same as original variable.

* [C] Fixed coding style issues

* add uncrustify support

* update petstore sampmles

* add Locale.ROOT

* added test-api-client.c to include test cases for strReplace function

* added header and body mustache and made changes to ClibcurlClientCodegen.java accordingly

* [C] renamed functions in apiKey.c.mustache according to apiKey.h.mustache

* [C] changes in import statement

* renamed apiKey.h to keyValuePair.h and made necessary changes in the codes

* changed apiKey.c according to keyValuePair.h

* fixed import statement in model

* added code for generating struct in model-header.mustache

* added typedef struct for model-headers

* updated sample/client/petstore/C

* fix locale

* [C] Function addition and modification of major structs (#1020)

* added readme file

* fixed parameters in api headers functions

* made changes to add readme file and typemapping of array to list

* fixed header import statement in apiheader files

* modified struct of model type in model header

* updated sample

* modified README file

* updated sample

* parse from json function added

* modified struct and create function

* added include for model

* modified parsefromjson function

* modified struct and create function for more datatypes

* added mapping for date-time and modified model import return statement

* modified function parameters

* modified include statement

* fix function in api body

* updated sample

* clean up files

* regenerate c petstore

* fix error message when setting uncrustify

* add version to uncrustify usage

* added uncrustify rules in  mustache (#1021)

* added uncrustify rules in  mustache

* updated sample

* updated same with crustify

* updated sample with uncrusitfy 0.67

* modified readme about uncrustify requirements

* fixed mistakes in readme mustache and sample readme

* fix file import, unformat c petstore

* fix import in test files

* fix model with complexType

* fix free string, format the code using uncrustify

* modified sample

* Modified sample to check

* return type issue figured,more to do to fix it

* minor fixes to make complete code compile

* Compiling sample code. Store has issue with map.

* comment out test file generation which is not req.

* commented operation name

* fixed various issues responsible for code not compiling

* test mustache temporary for testing

* updated sample add,del,getbyid works, formparam yet to do

* few minor changes and added fuction to add different header and content type in apiClient

* added code to upload image

* added function to test upload image

* fixes for fileupload and various other small things

* fixed issue due to xml produces

* updated sample:working sample add,del,find,uploading:tocheck ,

* added free functions for variable where memory is allocated

* rename imagecontainer struct to filestruct

* fix issues with if functions for all list types

* fixed issue with primitive return type in header file

* updated sample w/ free functions

* update c samples

* remove corrupted file

* update samples

* test cases for APIs

* added function to generate test cases from new mustache

* mustache files for manual written test cases

* added default content type to application/json

* fixed issue with primitive return type

* fixed issue with bool type

* added file apiKey.c

* updated sample tested

* update c environment variable (#1090)

* add mapping for map (#1103)

* minor update

* revert list paramter check to NULL

* modified return type for primitive(map - list_t)in mustache

* removed apiClient_free as it was two times

* updated sample

* fixed issue of path parameter when string less than parameter len

* fixed issue for form paramters upload

* added checks to avoid seg faults

* updated sample

* added check for null value in form parameter

* modified size of mallocs to dynamic

* updated sample

* Add C Petstore to Travis CI (#1136)

* setup CI for C petstore

* update bash script permission

* unit petapi test

* fixed memory leak in strReplace and apiClient Functions

* modified return value for status generation

* added enum defination and functions to convert and back from string

* added function for enum and made changes to free memory at necessary places

* added datatype handling for enum

* fixes regarding memory allocation and free

* updated mustache of test files

* updated sample

* renamed manually written test files

* manual test file for pet

* cleaned common api test file for time being

* renamed test files

* added renamed test files to build test bash

* added file null pointer check

* modified uncrusitfy rules

* minor update to c templates (#1161)

* [C] Fixed enum function declaration  (#1178)

* fixed enum function declaration in model headers

* fixed enum declaration in header files for sample

* disable curl verbose mode and add response code variable

* added response code variable in apiClient struct

* modified apiClient header and source file

* added response and removed commented code api-body mustache

* removed commented code from model-body mustache

* removed unnecessary print statements from test mustache

* updated sample

* fixed spaces issue

* Better format in C templates (#1224)

* better format in the c template

* minor format fix

* [C] changed base url from static to dynamic (#1225)

* changed basePath from static to dynamic

* removed unnecessary header declaration

* updated sample

* [C] added curl version check in CMakeList.txt (#1248)

* added curl version check in CMakeList.txt

* Updated README for latest curl version

* [C] Major changes to keyValuePair function (#1282)

* removed static declaration

* changed static declaration

* added difference for string and non string

* added more code for different function for string and non string

* fix issue with param name

* change value in keyPairValue to void

* fixed issue of difference in function name cases

* added support for non char parameters in api

* fix issue of map return data

* modified manual-StoreAPI map return data handling

* fix minor mistake

* added support for map and changed code to support value of keyvaluepair as char and other

* updated sample

* fixed api header declarations

* change map declaration in header

* resolved issues realted to map data handling

* fix minor issues

* add N at start if enum variable starts with number

* override toParamName method

* changed paramters to paramName from baseName

* change variables in apibody from baseName to paramName

* Skip test file generation (#1459)

* skip test file generation

* skip overwriting CMakeLists.txt
2018-11-17 01:32:18 +08:00
William Cheng
6ab6896a13 comment out dart2 test, update rust server samples (#1471) 2018-11-17 01:27:07 +08:00
Benjamin Gill
32b8d7fee7 [rust-server] Always derive Debug (#1404)
* Add test for file response

* Always derive Debug

Now that we're using a byte array, we can guarantee that deriving Debug will always work
2018-11-16 12:28:05 +00:00
Shengpeng Liu
dc3a3dd15a Fix openapi_types generation error (#1256) 2018-11-15 21:38:45 +08:00
William Cheng
736e8348b6 update documentation for a generator 2018-11-15 18:32:12 +08:00
William Cheng
2bcf5b2263 Merge remote-tracking branch 'origin/3.4.x' into 4.0.x 2018-11-15 17:49:44 +08:00
William Cheng
a87a544bf5 Merge remote-tracking branch 'origin/master' into 3.4.x 2018-11-15 17:11:01 +08:00
William Cheng
8d9542207a Prepare 3.3.4 snapshot (#1450)
* change version to 3.3.4-snapshot

* updat readme

* update samples
2018-11-15 16:21:15 +08:00
William Cheng
31d9928734 Revert "force deployment"
This reverts commit e5c0d227ab.
2018-11-15 12:25:14 +08:00
William Cheng
e5c0d227ab force deployment 2018-11-15 11:39:14 +08:00
James Addyman
653601bef2 Fix #1424 [SWIFT4] Date Encoding Issues (#1442)
Ensure the same date format string is used throughout the generated code (use the one set in Configuration.swift).

Ensure the same date formatter options are used when encoding dates as well as decoding dates. If a consumer has set their own date formatter on CodableHelper, use that when encoding dates too.

Adds DateFormatTests to the SWIFT4 unit tests.

Updates the SWIFT4 petstore samples
2018-11-15 11:20:39 +09:00
William Cheng
7564d629e7 prepare 3.3.3 release (#1447) 2018-11-14 23:56:58 +08:00
William Cheng
f647b2f24b Add file post-processing to C++ client, server generators (#1440)
* add file post processing to cpp generators

* use clang to auto format cpp-restsdk code

* restore cpp-restsdk samples without clang format
2018-11-14 16:43:14 +08:00
William Cheng
0165b0fb33 test all generators with fake petstore spec 2.0, 3.0 (#1439) 2018-11-14 15:55:09 +08:00
Jim Schubert
df1819daa9 C# template refactor (#737)
* [csharp] Refactor to support third-party customization more easily

* [csharp] Regenerate OpenAPIClient sample

* create new csharp-refactor client gen

* update samples

* fix Locale.ROOT

* fix import

* remove outdated files, update samples
2018-11-14 14:41:42 +08:00
William Cheng
3c28946f1e [Android] Fix compilation errors when there's no model defined (#1438)
* remove model import when there is no model

* fix android http client no model issu due to import
2018-11-14 14:02:05 +08:00
TNM Technologies
22902e72a1 fix(#1423): [JAVA] generating Map with jaxrs-reasteasy does not import (#1426)
* fix(#1423): [JAVA] generating Map with jaxrs-reasteasy does not import
the hashmap

https://github.com/OpenAPITools/openapi-generator/issues/1423

* fix(#1423): fix ensure-up-to-date issues for jaxrs-resteasy joda
samples

https://github.com/OpenAPITools/openapi-generator/issues/1423
2018-11-14 10:18:53 +08:00
William Cheng
efde4a8eb8 Fix issue with C# generator when the model name is "File" (#1428)
* fix get schema type in abstract c# class

* update c# petstore sample
2018-11-14 09:43:31 +08:00
Akihito Nakano
c8837ea414 Change entrypoint to docker-entrypoint.sh (#1413)
Run entrypoint script
2018-11-13 17:24:04 +09:00
William Cheng
7c3a2a5c07 Fix run-in-docker by disabling useSystemClassLoader (#1418)
* test run-in-docker in travis

* fix command path

* correct batch mode arg

* disable useSystemClassLoader
2018-11-12 22:07:46 +08:00
William Cheng
7e3149e675 fix npe when paramName is null (#1416) 2018-11-12 22:06:58 +08:00
meganemura
9db62f459a Fix return_type parameter examples in ruby-client (#1399)
* Fix return_type parameter examples

* $ bin/openapi3/ruby-client-petstore.sh
2018-11-12 14:26:05 +08:00
William Cheng
c7349c7f88 Add top level x-group-parameters support (#1405)
* add top level x-group-parameters support

* update petstore samples
2018-11-12 14:25:32 +08:00
William Cheng
69a766882d Add tip about running online openapi-generator via Docker (#1415)
Add tip about running online openapi-generator via Docker
2018-11-12 11:37:30 +08:00
William Cheng
7ce38aae38 Remove duplicated imports (#1414)
* remove duplicated imports

* fix model import in java

* update generator docs

* fix model import for retrofit2 client
2018-11-11 21:33:28 +08:00
sunn
fd46b4e566 Sanitize Model Import (#1411) 2018-11-10 21:07:49 +01:00
James Addyman
5711985ac3 Fix swift4 1406 (#1407)
* Fix warnings produced when using Swift 4.2

* Update Petstore client for Swift 4
2018-11-10 13:59:58 +09:00
William Cheng
7c6beb9692 update generator doc 2018-11-10 00:28:08 +08:00
sunn
8ba4b3a276 Sanitize names in case number is present (#1409) 2018-11-09 16:53:30 +01:00
Simas Abramovas
f802e63f9f Add parcelizeModels cli option (#1289)
* Add parcelizeModels cli option

* Add info log to clarify the parcelization requirements.

* Update docs
2018-11-09 23:51:27 +08:00
sunn
0ed02c8e91 Fixes double prefixing during model import (#1398) 2018-11-09 16:49:47 +01:00
Eivind Bergstøl
93e2fc6355 Fixes an issue where code generator for Java produces not compileable (#1357)
code if the yml-definition does not have any type definitions. This
is normal if the api only uses simple datatypes (Int, String) for
inout/output.
2018-11-09 23:48:26 +08:00
William Cheng
60bc19e830 Add file post-processing to PHP generators (#1402)
* add file post processing to php

* restore php petstore client
2018-11-09 23:45:21 +08:00
William Cheng
d59230fd27 change python pool_thread default to 1 (#1403) 2018-11-09 23:44:47 +08:00
Benjamin Gill
4742f0086b [rust-server] Re-instate ApiRequestParser (#1388)
* Re-instate ApiRequestParser

It turns out I was over-eager when removing file support and accidentally deleted some code that should have been kept. See https://github.com/OpenAPITools/openapi-generator/pull/547/files#diff-684007b298ee5998fa30732c261ea2fcL469.

* Don't do html escaping of parameters
2018-11-09 11:23:59 +00:00
William Cheng
1522855915 update python petstore samples 2018-11-08 21:47:16 +08:00
sunn
75b1403c1e [cpp-qt5] improvements for server and client (#1284)
- Remove pointer usage in generated models
- Use const reference wherever possible
- Reuse same super class for Qt5 client and server
- Support primitive return types for Qt5 client
- Add const reference to API calls
2018-11-08 14:18:57 +01:00
William Cheng
a023a0d0ca update petstore samples 2018-11-08 18:32:48 +08:00
William Cheng
e6c97a1bc1 Merge remote-tracking branch 'origin/3.4.x' into 4.0.x 2018-11-08 18:18:12 +08:00
William Cheng
a186efed35 Merge remote-tracking branch 'origin/master' into 3.4.x 2018-11-08 18:17:29 +08:00
William Cheng
3969afb2ff Add file post-processing to Kotlin generators (#1400)
* add post processing to kotlin file

* restore kotlin samples
2018-11-08 17:40:39 +08:00
William Cheng
2ef499faf3 [python] Avoid creating unused ThreadPools (#1387)
* Avoid creating unused ThreadPools

Instead, create ApiClient.pool on first request for .pool property.

avoids spawning n-cpus threads (the default for ThreadPool) at instantiation of every ApiClient

* update doc

* set pool_thread to None
2018-11-08 17:39:20 +08:00
William Cheng
34945427d4 fix java exception in apex codegen (#1395) 2018-11-07 22:32:22 +08:00
Benjamin Gill
5849dbaaca Add tests for inline objects (#1331)
I think these tests cover all the problems with rust-server and inline objects I know about. This should show us when we've fixed the problem.

Also fixes a CI failure.
2018-11-07 11:07:53 +00:00
Steven Masala
73162cbcca fix name sanitation when using kebab case filenaming (#1314)
* fix name sanitation when using kebab case filenaming

* remove whitespaces
2018-11-07 15:52:51 +08:00
Guy Gershoni
0e2e1bf715 Added tests and fix for issue #1392. Fix regex generated in Ruby client. (#1393)
* Added tests and fix for issue #1392. Param validation with regex not recognizing \d correctly in Ruby client.

* Added generated files to pass ./bin/utils/ensure-up-to-date which is run by circleci
2018-11-07 12:08:23 +08:00
William Cheng
f21640f6a1 update spring samples 2018-11-07 11:46:17 +08:00
Konstantin Pavlov
301208a785 JavaSpring: pojo: fix javadoc comment (#1384) 2018-11-07 11:26:56 +08:00
William Cheng
4245cf42dd update generator doc 2018-11-07 01:02:44 +08:00
Christophe Bornet
2184a8a9b4 [Flask] Upgrade to flask-connexion 2.0.0 (#1382)
Fix #323
2018-11-06 18:37:50 +08:00
Benjamin Gill
30bfebfa16 Rust server html (#1329)
Builds on #1180 by @colelawrence. This addition to the rust-server generator enables the use of text/html responses as plaintext.

I've added an html endpoint to the sample to demonstrate that this works (and fixed the problem that that uncovered).
2018-11-05 16:14:23 +00:00
Martin Fidczuk
303b469fae Allow package version to be passed on CLI (Rust fix) (#1286)
This MR allows package version to be specified in Rust in the generate argument list, with the argument `-DpackageVersion=<package_version>`. If this argument is present then the version in the resulting Cargo.toml file will be the passed value. If this argument is not present then the version in the OpenAPI definition file will be used, as per current behavior.
2018-11-05 16:12:43 +00:00
William Cheng
c95b1f4545 fix incorrect patternin aspnetcore (#1371) 2018-11-05 10:21:55 +08:00
William Cheng
fbc3ff8766 Add a link to an article about openapi-generator (#1370) 2018-11-05 08:17:22 +08:00
Nathan Broadbent
63b1c233c9 Fix issue with Ruby client where strings from example properties are not wrapped with quotes (#987) 2018-11-04 17:10:35 +08:00
andreas-eternach
eb5a8cc752 feat: OpenApi-generation from within eclipse (#509) (#1332)
* feat: OpenApi-generation from within eclipse (#509)

* Added life-cycle-mapping for recognition by M2E
* Make BuildContext injectable by M2E in oder to detect if json-source
has been modified and a regeneration is required.

* core: fix indentation problems, remove commented code
2018-11-04 17:07:33 +08:00
Benoît Courtine
293d29ab3b Fixes bug #1339. Array and Map inner schema can be missing. In this case, it must default to String. (#1363) 2018-11-03 22:19:19 +08:00
Kiran-Sivakumar
078b04deac [Java][okhttp-gson] Add new ApiClient constructors for access token retry (#1319)
* Add new ApiClient constructors for access token retry

* Update samples

* Update security samples
2018-11-03 22:10:16 +08:00
Kay Schecker
7eb9cda1e0 Added hint for npm package wrapper to README (#1350)
* Added hint for npm package wrapper to README

* Added manual how to use and install NPM package globally
2018-11-03 22:06:11 +08:00
Vasili Puchko
ac6fd3f79f Update gradle plugin's Readme.md (#1356)
Add a note about use of `systemProperties` since some options are confusing and hard to guess how to use correctly. The only source I was able to find how to configure it in the way I need was a comment to issue https://github.com/OpenAPITools/openapi-generator/issues/551#issuecomment-411686091
2018-11-03 21:58:43 +08:00
sunn
f8f3a08282 [cpp-pistache]Add support for map (#1359)
* Add support for map
* Add support for nested maps
* Simplify Array and Map Helper
* Use const reference wherever possible
2018-11-03 14:09:31 +01:00
William Cheng
36991a4e14 Improve ensure-up-to-date script (#1362)
* improve ensure-up-to-date script

* trigger build failure

* use exit 1 instead

* fix build failure

* update samples
2018-11-02 15:38:34 +08:00
Juan Eugenio Abadie
ecff8b5d00 [cpp rest-sdk]Fix precision (#1293)
* Convert floating point numbers to string with higher precision
* Update PetStore
2018-11-01 20:25:38 +01:00
Ysawa
521f5fafa3 Fix defaultValue for String schama in Dart (#1342) 2018-11-01 17:50:01 +08:00
William Cheng
02e85cc417 Prepare v3.3.3-SNAPSHOT (#1355)
* prepare 3.3.3-snapshot

* update petstore samples
2018-11-01 10:42:26 +08:00
William Cheng
ceffdde2c0 update samples 2018-10-26 23:27:06 +08:00
William Cheng
71ecee02e9 Merge remote-tracking branch 'origin/3.4.x' into 4.0.x 2018-10-26 23:13:28 +08:00
William Cheng
ed2f6ea72e Merge branch '3.4.x' of https://github.com/openapitools/openapi-generator into 3.4.x 2018-10-26 22:30:19 +08:00
William Cheng
ef98971746 update samples 2018-10-26 21:43:38 +08:00
William Cheng
3482a0a993 Merge remote-tracking branch 'origin/master' into 3.4.x 2018-10-26 21:04:25 +08:00
William Cheng
4a47acce19 Merge remote-tracking branch 'origin/3.4.x' into 4.0.x 2018-10-26 18:41:58 +08:00
William Cheng
9422dea149 Merge remote-tracking branch 'origin/master' into 3.4.x 2018-10-26 18:40:37 +08:00
Yuriy Belenko
30062afc7c [Slim] Migration to PHP7 (#1263)
* [Slim] Add PHP 7.0 to requirements

* [Slim] Migrate to PHPUnit 6

* [Slim] Update user guide

* [Slim] Refresh samples
2018-10-26 18:15:41 +08:00
Fabrizio Ferrai
bbfaa90242 [Clojure] Fix tests: stop dashizing props names (#1310)
* [Clojure] Fix tests: stop dashizing props names

* [Clojure] Remove jdk7 tests
2018-10-25 12:19:52 +08:00
tca-ms
eccab2c025 Better context errors (#1198)
Update to version 2 of the `swagger` crate, which contains changes intended to make it easier to debug errors involving middleware and contexts. Crates making use of the autogenerated libraries to also update their swagger dependency to version 2. See [here](https://github.com/Metaswitch/swagger-rs/blob/2.0.0/CHANGELOG.md) for details.
2018-10-17 17:14:43 +01:00
William Cheng
40e90b5883 Merge remote-tracking branch 'origin/3.4.x' into 4.0.x 2018-10-17 00:06:12 +08:00
William Cheng
a3dc5ecc20 Merge remote-tracking branch 'origin/master' into 3.4.x 2018-10-17 00:05:47 +08:00
William Cheng
649d5a97b4 remove unused pom for circleci 2018-10-16 23:53:06 +08:00
William Cheng
83c55ec016 Merge remote-tracking branch 'origin/3.3.x' into 4.0.x 2018-10-16 23:42:29 +08:00
William Cheng
e42cac636a update clojure petstore samples 2018-10-16 18:06:05 +08:00
William Cheng
cfbc72f444 Merge branch '4.0.x' of https://github.com/openapitools/openapi-generator into 4.0.x 2018-10-16 16:16:28 +08:00
William Cheng
9e3c7781bb Merge remote-tracking branch 'origin/3.4.x' into 4.0.x 2018-10-16 16:08:11 +08:00
William Cheng
257a97b6cd update petstore samples 2018-10-16 13:19:40 +08:00
William Cheng
5490bb8e9c update petstore 2018-10-03 18:36:12 +08:00
William Cheng
0f7557ca9d update version 2018-10-03 18:29:29 +08:00
William Cheng
5357791337 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-10-01 16:38:26 +08:00
William Cheng
c9625f3fd5 update petstore samples 2018-09-13 22:51:16 +08:00
William Cheng
94eb1c3c63 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-09-13 22:46:21 +08:00
Jeremie Bresson
a08f8d13e0 Merge remote-tracking branch 'origin/3.3.x' into 4.0.x
Conflicts:
	modules/openapi-generator-online/Dockerfile
	samples/*
2018-08-26 09:13:39 +02:00
William Cheng
adbe478e0b fix toLowerCase with Locale.ROOT 2018-08-23 18:58:26 +08:00
William Cheng
780ba49da1 Merge remote-tracking branch 'origin/3.3.x' into 4.0.x 2018-08-23 18:39:54 +08:00
William Cheng
e5b6d525c7 update ruby pestore client 2018-08-16 01:34:25 +08:00
William Cheng
d1f7e16daa Merge branch '3.3.x' into 4.0.x 2018-08-16 01:01:34 +08:00
Fabrizio Ferrai
74d70121d1 [Clojure] Add model generation and conforming (#122)
* [Clojure] Add model generation and verification

- Generate clojure.specs from models
- Optionally validate them at runtime (validation is active if
  orchestra.spec.test/instrument is called after specs are imported)
- Coerce the results of the API calls to get objects that conform
  to the spec (e.g. get Date objects for dates and time instead of strings)

* [Clojure] Make model conforming configurable and opt-out

* [Clojure] Move specs from a single file to a ns per model

So that the order of the forms will be resolved by the compiler,
otherwise we'd have to implement a topological ordering.

* [Clojure] Update petstore sample and set automatic decoding off

* [Clojure] Stop testing Clojure generator on Java7

* [Clojure] Fix tests and handling of multiple arity

* [Clojure] Fix tests and add testing for the new decoding feature

* [Clojure] Capitalize names of generated models

* [Clojure] Rename petstore specs to be capitalized

* Revert to lowercase spec names, and postfix the data specs
2018-08-13 15:04:25 +08:00
stkrwork
aed8e38584 Merge branch '3.3.x' into 4.0.x 2018-08-07 17:11:21 +02:00
William Cheng
3746fae2ca Merge remote-tracking branch 'origin/3.3.x' into 4.0.x 2018-08-07 16:04:17 +08:00
William Cheng
c44d91c673 update petstore samples 2018-08-03 12:36:57 +08:00
William Cheng
be2a0170b7 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-08-03 00:10:34 +08:00
William Cheng
2f85867963 update php lumen samples 2018-07-28 10:39:17 +08:00
William Cheng
3b1029ada4 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-07-28 01:12:00 +08:00
William Cheng
8cbd57d829 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-07-27 00:29:44 +08:00
William Cheng
75e5ed2f68 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-07-26 22:51:23 +08:00
Jeremie Bresson
6460bb2897 Merge remote-tracking branch 'origin/master' into 4.0.x 2018-07-25 22:07:47 +02:00
William Cheng
22c79cf470 update petstore samples 2018-07-24 11:01:07 +08:00
William Cheng
024dde11d7 Merge remote-tracking branch 'origin/3.2.x' into 4.0.x 2018-07-23 23:05:25 +08:00
William Cheng
d2db799a93 update petstore samples 2018-07-19 19:06:48 +08:00
William Cheng
07b8040122 Merge remote-tracking branch 'origin/3.2.x' into 4.0.x 2018-07-19 18:56:13 +08:00
Jeremie Bresson
eb09731a65 Merge remote-tracking branch 'origin/3.2.x' into 4.0.x 2018-07-18 12:32:55 +02:00
William Cheng
f98000753d update petstore samples 2018-07-16 16:59:45 +08:00
William Cheng
deb5dcaad1 Merge remote-tracking branch 'origin/3.2.x' into 4.0.x 2018-07-14 01:42:02 +08:00
Jeremie Bresson
7f4fc4de93 Merge remote-tracking branch 'origin/3.2.x' into 4.0.x 2018-07-07 15:29:36 +02:00
Jeremie Bresson
7938677efa Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 2018-06-28 07:04:03 +02:00
Jeremie Bresson
b0c02d8ea6 Merge remote-tracking branch 'origin/3.1.x' into 4.0.x
# Conflicts:
#	samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION
#	samples/server/petstore/kotlin-server/ktor/README.md
#	samples/server/petstore/php-silex/.openapi-generator/VERSION
2018-06-25 19:09:41 +02:00
William Cheng
05f177b6d6 [PHP-Lumen] Lumen 5.6 support (#212)
* Lumen 5.6 support

* recall headlines

* Update composer.mustache

* regenerate lumne php petstore samples

* remove output format from lumen routes

* Fix: "A facade root has not been set"

* Ignore log folder
2018-06-16 19:07:13 +08:00
William Cheng
b1921ce484 Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 2018-06-16 19:03:14 +08:00
Jeremie Bresson
4a4fb77081 Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 2018-06-14 13:30:57 +02:00
Jeremie Bresson
f5f744ad2c Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 2018-06-12 19:38:40 +02:00
Jeremie Bresson
b887efdc1c Initial commit for 4.0.0-SNAPSHOT 2018-06-12 06:40:07 +02:00
2892 changed files with 114202 additions and 28701 deletions

View File

@@ -2,7 +2,7 @@
- [ ] Read the [contribution guidelines](https://github.com/openapitools/openapi-generator/blob/master/CONTRIBUTING.md).
- [ ] Ran the shell script under `./bin/` to update Petstore sample so that CIs can verify the change. (For instance, only need to run `./bin/{LANG}-petstore.sh` and `./bin/security/{LANG}-petstore.sh` if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates). Windows batch files can be found in `.\bin\windows\`.
- [ ] Filed the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `3.4.x`, `4.0.x`. Default: `master`.
- [ ] Filed the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`~~, `3.4.x`, `4.0.x`~~. Default: `master`.
- [ ] Copied 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.
### Description of the PR

7
.gitignore vendored
View File

@@ -184,6 +184,9 @@ samples/server/petstore/kotlin-server/ktor/build
.stack-work
.cabal-sandbox
cabal.project.local
samples/client/petstore/haskell-http-client/docs/haddock-bundle.min.js
samples/client/petstore/haskell-http-client/docs/meta.json
samples/client/petstore/haskell-http-client/docs/quick-jump.css
# R
.Rproj.user
@@ -212,3 +215,7 @@ samples/client/petstore/javascript/package-lock.json
# elm
samples/client/petstore/elm/index.html
# C
samples/client/petstore/c/build
samples/client/petstore/c/*.so

View File

@@ -75,11 +75,14 @@ before_install:
- sudo apt-get install -qq curl
# install dart
#- sudo apt-get update
- sudo apt-get install apt-transport-https
- sudo sh -c 'curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -'
- sudo sh -c 'curl https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list'
- sudo apt-get update
- sudo apt-get install dart
#- sudo apt-get install apt-transport-https
#- sudo sh -c 'curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -'
#- sudo sh -c 'curl https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list'
#- sudo apt-get update
#- sudo apt-get install dart
# switch to php7
- phpenv global 7.1
- php -v
# install perl module
#- cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
#- cpanm Test::Exception Test::More Log::Any LWP::UserAgent JSON URI:Query Module::Runtime DateTime Module::Find Moose::Role
@@ -109,8 +112,8 @@ install:
- gcc -v
- echo $CC
- echo $CXX
- pub version
- dart --version
#- pub version
#- dart --version
script:
# fail fast
@@ -122,8 +125,8 @@ script:
# fail if generators contain tab '\t'
- /bin/bash ./bin/utils/detect_tab_in_java_class.sh
# run integration tests defined in maven pom.xml
- mvn --quiet clean install
- mvn --quiet verify -Psamples
- ./run-in-docker.sh mvn --quiet --batch-mode clean install
- mvn --quiet --batch-mode verify -Psamples
after_success:
# push to maven repo
- if [ $SONATYPE_USERNAME ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
@@ -148,7 +151,7 @@ after_success:
## docker: build and push openapi-generator-online to DockerHub
- if [ $DOCKER_HUB_USERNAME ]; then echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin && docker build -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/openapi-generator-online && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_GENERATOR_IMAGE_NAME && echo "Pushed to $DOCKER_GENERATOR_IMAGE_NAME"; fi; fi
## docker: build cli image and push to Docker Hub
- if [ $DOCKER_HUB_USERNAME ]; then echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin && docker build -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME && echo "Pushed to $DOCKER_CODEGEN_CLI_IMAGE_NAME"; fi; fi
- if [ $DOCKER_HUB_USERNAME ]; then echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin && cp docker-entrypoint.sh ./modules/openapi-generator-cli && docker build -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME && echo "Pushed to $DOCKER_CODEGEN_CLI_IMAGE_NAME"; fi; fi
env:
- DOCKER_GENERATOR_IMAGE_NAME=openapitools/openapi-generator-online DOCKER_CODEGEN_CLI_IMAGE_NAME=openapitools/openapi-generator-cli NODE_ENV=test CC=gcc-5 CXX=g++-5

View File

@@ -15,7 +15,7 @@ elif [ "$NODE_INDEX" = "2" ]; then
java -version
#export GO_POST_PROCESS_FILE="/usr/local/bin/gofmt -w"
# not formatting the code as different go versions may format the code a bit different
#./bin/utils/ensure-up-to-date
./bin/utils/ensure-up-to-date
else
echo "Running node $NODE_INDEX to test 'samples.circleci.jdk7' defined in pom.xml ..."
sudo update-java-alternatives -s java-1.7.0-openjdk-amd64

View File

@@ -0,0 +1,26 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptAngularBuildPestoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Fetch Default Petstore Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,59 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptAngularBuildES6PestoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Fetch ES6 Petstore Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,73 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptAngularBuildWithNPMVersionPestoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Fetch Petstore Client (with npm)</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-build</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,59 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptFetchPestoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Fetch Petstore Test Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>pre-integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -2,20 +2,11 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`3.3.2`): [![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.0.0`): [![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)
[`3.4.x`](https://github.com/OpenAPITools/openapi-generator/tree/3.4.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/3.4.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/3.4.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=3.4.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=3.4.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[`4.0.x`](https://github.com/OpenAPITools/openapi-generator/tree/4.0.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/4.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/4.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=4.0.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=4.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
</div>
<div align="center">
@@ -47,11 +38,11 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
|-|-|
**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C#** (.net 2.0, 3.5 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 7.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node)
**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 7.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node)
**Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed), **Erlang**, **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin** (Spring Boot), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), Scalatra)
**API documentation generators** | **HTML**, **Confluence Wiki**
**Configuration files** | [**Apache2**](https://httpd.apache.org/)
**Others** | **JMeter**, **MySQL Schema**
**Others** | **GraphQL**, **JMeter**, **MySQL Schema**
## Table of contents
@@ -65,6 +56,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
- [1.4 - Build Projects](#14---build-projects)
- [1.5 - Homebrew](#15---homebrew)
- [1.6 - Docker](#16---docker)
- [1.7 - NPM](#17---npm)
- [2 - Getting Started](#2---getting-started)
- [3 - Usage](#3---usage)
- [3.1 - Customization](#31---customization)
@@ -87,10 +79,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
OpenAPI Generator Version | Release Date | Notes
---------------------------- | ------------ | -----
4.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.0.0-SNAPSHOT/)| TBD | Major release with breaking changes (no fallback)
3.4.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/3.4.0-SNAPSHOT/)| 01.11.2018 | Minor release (breaking changes with fallbacks)
3.3.2 (current master, upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/3.3.2-SNAPSHOT/) | 31.10.2018 | Bugfix release
[3.3.2](https://github.com/OpenAPITools/openapi-generator/releases/tag/v3.3.2) (latest stable release) | 31.10.2018 | Bugfix release
4.0.0 (upcoming release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.0.0-SNAPSHOT/)| 20.12.2018 | Major release with breaking changes (with or without fallback)
[3.3.4](https://github.com/OpenAPITools/openapi-generator/releases/tag/v3.3.4) (latest stable release) | 30.11.2018 | Bugfix release
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
@@ -146,16 +136,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository.
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/3.3.2/openapi-generator-cli-3.3.2.jar`
JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.3.4/openapi-generator-cli-3.3.4.jar`
For **Mac/Linux** users:
```sh
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.3.2/openapi-generator-cli-3.3.2.jar -O openapi-generator-cli.jar
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.3.4/openapi-generator-cli-3.3.4.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/3.3.2/openapi-generator-cli-3.3.2.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.3.4/openapi-generator-cli-3.3.4.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@@ -215,7 +205,7 @@ To build from source, you need the following installed and available in your `$P
* [Java 8](http://java.oracle.com)
* [Apache maven 3.3.3 or greater](http://maven.apache.org/)
* [Apache maven 3.3.4 or greater](http://maven.apache.org/)
After cloning the project, you can build it from source with this command:
```sh
@@ -284,13 +274,13 @@ GEN_IP=$(docker inspect --format '{{.NetworkSettings.IPAddress}}' $CID)
-d '{"openAPIUrl": "https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml"}' \
'http://localhost:8888/api/gen/clients/ruby'
{"code":"c2d483d3-3672-40e9-91df-b9ffd18d22b8","link":"http://localhost:8888/api/gen/download/c2d483d3-3672-40e9-91df-b9ffd18d22b8"}
{"code":"c2d483.3.4672-40e9-91df-b9ffd18d22b8","link":"http://localhost:8888/api/gen/download/c2d483.3.4672-40e9-91df-b9ffd18d22b8"}
# Download the generated zip file
> wget http://localhost:8888/api/gen/download/c2d483d3-3672-40e9-91df-b9ffd18d22b8
> wget http://localhost:8888/api/gen/download/c2d483.3.4672-40e9-91df-b9ffd18d22b8
# Unzip the file
> unzip c2d483d3-3672-40e9-91df-b9ffd18d22b8
> unzip c2d483.3.4672-40e9-91df-b9ffd18d22b8
# Shutdown the openapi generator image
> docker stop $CID && docker rm $CID
@@ -346,6 +336,30 @@ cd /vagrant
./run-in-docker.sh mvn package
```
### [1.7 - NPM](#table-of-contents)
There is also an [NPM package wrapper](https://www.npmjs.com/package/@openapitools/openapi-generator-cli) available for different platforms (e.g. Linux, Mac, Windows). (JVM is still required)
Please see the [project's README](https://github.com/openapitools/openapi-generator-cli) there for more information.
Install it globally to get the CLI available on the command line:
```sh
npm install @openapitools/openapi-generator-cli -g
openapi-generator version
```
Or install a particualar OpenAPI Generator version (e.g. v3.3.4):
```sh
npm install @openapitools/openapi-generator-cli@cli-3.3.4 -g
```
Or install it as dev-dependency:
```sh
npm install @openapitools/openapi-generator-cli -D
```
## [2 - Getting Started](#table-of-contents)
To generate a PHP client for [petstore.yaml](https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml), please run the following
@@ -451,7 +465,7 @@ Other languages have petstore samples, too:
./bin/objc-petstore.sh
```
... and others. [Here is a list of all scripts.](wiki/Samples-folder#scripts)
... and others. [Here is a list of all scripts.](https://github.com/OpenAPITools/openapi-generator/wiki/Samples-folder#scripts)
### [3.1 - Customization](#table-of-contents)
@@ -463,6 +477,15 @@ Please refer to [integration.md](docs/integration.md) on how to integrate OpenAP
### [3.3 - Online OpenAPI generator](#table-of-contents)
Here are the public online services:
- latest stable version: http://api.openapi-generator.tech
- latest master: http://api-latest-master.openapi-generator.tech (updated with latest master every hour)
The server is sponsored by [Linode](https://www.linode.com/) [![Linode Logo](https://www.linode.com/media/images/logos/standard/light/linode-logo_standard_light_small.png)](https://www.linode.com/)
(These services are beta and do not have any guarantee on service level)
Please refer to [online-openapi-generator.md](docs/online-openapi-generator.md) on how to run and use the `openapi-generator-online` - a web service for `openapi-generator`.
### [3.4 - License information on Generated Code](#table-of-contents)
@@ -478,6 +501,7 @@ When code is generated from this project, it shall be considered **AS IS** and o
Here are some companies/projects (alphabetical order) using OpenAPI Generator in production. To add your company/project to the list, please visit [README.md](README.md) and click on the icon to edit the page.
- [Angular.Schule](https://angular.schule/)
- [b<>com](https://b-com.com/en)
- [Bithost GmbH](https://www.bithost.ch)
- [Boxever](https://www.boxever.com/)
- [GMO Pepabo](https://pepabo.com/en/)
@@ -489,6 +513,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [REST United](https://restunited.com)
- [Suva](https://www.suva.ch/)
- [Telstra](https://dev.telstra.com)
- [TUI InfoTec GmbH](http://www.tui-infotec.com/)
- [unblu inc.](https://www.unblu.com/)
- [Zalando](https://www.zalando.com)
@@ -503,7 +528,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2018/07/19 - [OpenAPI Generator Contribution Quickstart - RingCentral Go SDK](https://medium.com/ringcentral-developers/openapi-generator-for-go-contribution-quickstart-8cc72bf37b53) by [John Wang](https://github.com/grokify)
- 2018/08/22 - [OpenAPI Generatorのプロジェクト構成などのメモ](https://yinm.info/20180822/) by [Yusuke Iinuma](https://github.com/yinm)
- 2018/10/31 - [A node package wrapper for openapi-generator](https://github.com/HarmoWatch/openapi-generator-cli)
- 2018/11/03 - [OpenAPI Generator + golang + Flutter でアプリ開発](http://ryuichi111std.hatenablog.com/entry/2018/11/03/214005) by [Ryuichi Daigo](https://github.com/ryuichi111)
- 2018/11/19 - [OpenAPIs are everywhere](https://youtu.be/-lDot4Yn7Dg) by [Jeremie Bresson (Unblu)](https://github.com/jmini) at [EclipseCon Europe 2018](https://www.eclipsecon.org/europe2018)
## [6 - About Us](#table-of-contents)
@@ -527,6 +553,7 @@ Here is a list of template creators:
* Akka-Scala: @cchafer
* Apex: @asnelling
* Bash: @bkryza
* C: @PowerOfCreation @zhemant
* C++ REST: @Danielku15
* C# (.NET 2.0): @who
* C# (.NET Standard 1.3 ): @Gronsak
@@ -590,6 +617,7 @@ Here is a list of template creators:
* Erlang Server: @galaxie
* Go Server: @guohuang
* Go (Gin) Server: @kemokemo
* GraphQL Express Server: @renepardon
* Haskell Servant: @algas
* Java MSF4J: @sanjeewa-malalgoda
* Java Spring Boot: @diyfr
@@ -617,6 +645,7 @@ Here is a list of template creators:
* Configuration
* Apache2: @stkrwork
* Schema
* GraphQL: @wing328
* MySQL: @ybelenko
#### How to join the core team
@@ -655,6 +684,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| Android | @jaz-ah (2017/09) |
| Apex | |
| Bash | @frol (2017/07) @bkryza (2017/08) @kenjones-cisco (2017/09) |
| C | @zhemant (2018/11) |
| C++ | @ravinikam (2017/07) @stkrwork (2017/07) @fvarose (2017/11) @etherealjoy (2018/02) @martindelille (2018/03) |
| C# | @mandrean (2017/08) @jimschubert (2017/09) |
| Clojure | |
@@ -664,6 +694,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| Elm | @trenneman (2018/09) |
| Erlang | @tsloughter (2017/11) @jfacorro (2018/10) @robertoaloi (2018/10) |
| Go | @antihax (2017/11) @bvwells (2017/12) @grokify (2018/07) @kemokemo (2018/09 |
| GraphQL | @renepardon (2018/12) |
| Groovy | |
| Haskell | |
| Java | @bbdouglas (2017/07) @JFCote (2017/08) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) |
@@ -672,7 +703,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| NodeJS/Javascript | @CodeNinjai (2017/07) @frol (2017/07) @cliffano (2017/07) |
| ObjC | |
| Perl | @wing328 (2017/07) |
| PHP | @jebentier (2017/07) @dkarlovi (2017/07) @mandrean (2017/08) @jfastnacht (2017/09) @ackintosh (2017/09) @ybelenko (2018/07) |
| PHP | @jebentier (2017/07) @dkarlovi (2017/07) @mandrean (2017/08) @jfastnacht (2017/09) @ackintosh (2017/09) @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) |
| R | |

32
bin/c-petstore.sh Executable file
View File

@@ -0,0 +1,32 @@
#!/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/C-libcurl -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g c -o samples/client/petstore/c $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
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 -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 $ags

View File

@@ -0,0 +1,17 @@
#!/bin/sh
# C# Petstore API client (.NET 3.5)
./bin/csharp-refactor-petstore.sh
# C# Petstore API client with PropertyChanged
./bin/csharp-refactor-property-changed-petstore.sh
# C# Petstore API client (v5.0 for .net standarnd 1.3+)
./bin/csharp-refactor-petstore-net-standard.sh
# C# Petstore API client (.NET 4.0)
./bin/csharp-refactor-petstore-net-40.sh
# C# Petstore API client (.NET 3.5)
./bin/csharp-refactor-petstore-net-35.sh

37
bin/csharp-refactor-petstore.sh Executable file
View File

@@ -0,0 +1,37 @@
#!/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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g csharp-refactor -o samples/client/petstore/csharp-refactor/OpenAPIClient --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C} $@"
java $JAVA_OPTS -jar $executable $ags
# restore csproj file
#echo "restore csproject file: CI/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj"
#cp ./CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj ./samples/client/petstore/csharp-refactor/OpenAPIClient/src/Org.OpenAPITools.Test/

View File

@@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cwiki -o samples/documentation/cwiki $@"
ags="generate -t modules/openapi-generator/src/main/resources/confluenceWikiDocs -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cwiki -o samples/documentation/cwiki $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,32 @@
#!/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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties $@"
ags="generate -t modules/openapi-generator/src/main/resources/dukescript -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g dukescript -o samples/client/petstore/dukescript $@"
java $JAVA_OPTS -jar $executable $ags

32
bin/graphql-schema-petstore.sh Executable file
View File

@@ -0,0 +1,32 @@
#!/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/graphql-schema -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g graphql-schema -o samples/config/petstore/graphql-schema -DpackageName=petstore $@"
java $JAVA_OPTS -jar $executable $ags

32
bin/graphql-server-petstore.sh Executable file
View File

@@ -0,0 +1,32 @@
#!/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/graphql-server -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g graphql-server -o samples/server/petstore/graphql-server -DpackageName=petstore $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g html -o samples/documentation/html $@"
ags="generate -t modules/openapi-generator/src/main/resources/htmlDocs -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g html -o samples/documentation/html $@"
java $JAVA_OPTS -jar $executable $ags

0
bin/mysql-schema-petstore.sh Normal file → Executable file
View File

View File

@@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-qt5-client -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g cpp-qt5 -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/3_0/petstore.yaml -g cpp-qt5-client -o samples/client/petstore/cpp-qt5 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,42 @@
#!/bin/bash
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
# Make sure that the working directory is the root dir
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "${SCRIPT_DIR}/../"
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
# Make sure that we are regenerating the sample by removing any existing target directory
TARGET_DIR="$SCRIPT_DIR/../../samples/server/petstore/graphql-server"
if [ -d "$TARGET_DIR" ]; then
rm -rf $TARGET_DIR
fi
executable="$SCRIPT_DIR/../../modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t $SCRIPT_DIR/../../modules/openapi-generator/src/main/resources/graphql-server -i $SCRIPT_DIR/../../modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g graphql-server -o $TARGET_DIR $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -25,8 +25,13 @@ then
mvn clean package
fi
# purge lib/doc folder
echo "purge ruby petstore lib, docs folder"
rm -Rf samples/openapi3/client/petstore/ruby/lib
rm -Rf samples/openapi3/client/petstore/ruby/docs
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/ruby-client -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ruby -c bin/ruby-petstore.json -o samples/client/petstore/ruby -DskipFormModel=true $@"
ags="generate -t modules/openapi-generator/src/main/resources/ruby-client -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ruby -c bin/ruby-petstore.json -o samples/openapi3/client/petstore/ruby -DskipFormModel=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

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

0
bin/springboot-virtualan-petstore-server.sh Normal file → Executable file
View File

View File

@@ -9,3 +9,7 @@
./bin/typescript-angular-v6-petstore-not-provided-in-root-with-npm.sh
./bin/typescript-angular-v6-petstore-provided-in-root.sh
./bin/typescript-angular-v6-petstore-provided-in-root-with-npm.sh
./bin/typescript-angular-v7-petstore-not-provided-in-root.sh
./bin/typescript-angular-v7-petstore-not-provided-in-root-with-npm.sh
./bin/typescript-angular-v7-petstore-provided-in-root.sh
./bin/typescript-angular-v7-petstore-provided-in-root-with-npm.sh

View File

@@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -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-v6-petstore-not-provided-in-root-with-npm.json -o samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm -D providedInRoot=false --additional-properties ngVersion=6.0.0 $@"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-angular -c bin/typescript-angular-v6-petstore-not-provided-in-root-with-npm.json -o samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm -D providedInRoot=false --additional-properties ngVersion=6.0.0 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test\resources/2_0/petstore.yaml -g typescript-angular -o samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default -D providedInRoot=false --additional-properties ngVersion=6.0.0 $@"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-angular -o samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default -D providedInRoot=false --additional-properties ngVersion=6.0.0 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,6 @@
{
"npmName": "@swagger/typescript-angular-petstore",
"npmVersion": "1.0.0",
"npmRepository" : "https://skimdb.npmjs.com/registry",
"snapshot" : false
}

View File

@@ -0,0 +1,32 @@
#!/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} -XX:MaxPermSize=256M -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-v7-petstore-not-provided-in-root-with-npm.json -o samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm -D providedInRoot=false --additional-properties ngVersion=7.0.0 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,32 @@
#!/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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-angular -o samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default -D providedInRoot=false --additional-properties ngVersion=7.0.0 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,6 @@
{
"npmName": "@swagger/typescript-angular-petstore",
"npmVersion": "1.0.0",
"npmRepository" : "https://skimdb.npmjs.com/registry",
"snapshot" : false
}

View File

@@ -0,0 +1,32 @@
#!/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} -XX:MaxPermSize=256M -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-v7-petstore-provided-in-root-with-npm.json -o samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm --additional-properties ngVersion=7.0.0 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,32 @@
#!/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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-angular -o samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default --additional-properties ngVersion=7.0.0 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -30,3 +30,5 @@ export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target $@"
java $JAVA_OPTS -jar $executable $ags
cp CI/samples.ci/client/petstore/typescript-fetch/builds/es6-target/pom.xml samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml
cp CI/samples.ci/client/petstore/typescript-fetch/tests/default/pom.xml samples/client/petstore/typescript-fetch/tests/default/pom.xml

View File

@@ -30,3 +30,5 @@ export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version $@"
java $JAVA_OPTS -jar $executable $ags
cp CI/samples.ci/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml
cp CI/samples.ci/client/petstore/typescript-fetch/tests/default/pom.xml samples/client/petstore/typescript-fetch/tests/default/pom.xml

View File

@@ -30,3 +30,5 @@ export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default $@"
java $JAVA_OPTS -jar $executable $ags
cp CI/samples.ci/client/petstore/typescript-fetch/builds/default/pom.xml samples/client/petstore/typescript-fetch/builds/default/pom.xml
cp CI/samples.ci/client/petstore/typescript-fetch/tests/default/pom.xml samples/client/petstore/typescript-fetch/tests/default/pom.xml

View File

@@ -10,34 +10,44 @@ echo "Please press CTRL+C to stop or the script will continue in 5 seconds."
sleep 5
# LIST OF SCRIPTS:
./bin/openapi3/ruby-client-petstore.sh > /dev/null 2>&1
./bin/java-petstore-all.sh > /dev/null 2>&1
./bin/java-jaxrs-petstore-server-all.sh > /dev/null 2>&1
./bin/openapi3/jaxrs-jersey-petstore.sh > /dev/null 2>&1
./bin/spring-all-pestore.sh > /dev/null 2>&1
./bin/kotlin-client-petstore.sh > /dev/null 2>&1
./bin/kotlin-client-string.sh > /dev/null 2>&1
./bin/kotlin-client-threetenbp.sh > /dev/null 2>&1
./bin/kotlin-server-petstore.sh > /dev/null 2>&1
./bin/mysql-schema-petstore.sh > /dev/null 2>&1
./bin/php-petstore.sh > /dev/null 2>&1
./bin/php-silex-petstore-server.sh > /dev/null 2>&1
./bin/php-symfony-petstore.sh > /dev/null 2>&1
./bin/php-lumen-petstore-server.sh > /dev/null 2>&1
./bin/php-slim-server-petstore.sh > /dev/null 2>&1
./bin/php-ze-ph-petstore-server.sh > /dev/null 2>&1
./bin/openapi3/php-petstore.sh > /dev/null 2>&1
./bin/typescript-angular-petstore-all.sh > /dev/null 2>&1
./bin/typescript-fetch-petstore-all.sh > /dev/null 2>&1
./bin/typescript-node-petstore-all.sh > /dev/null 2>&1
./bin/typescript-inversify-petstore.sh > /dev/null 2>&1
./bin/rust-server-petstore.sh > /dev/null 2>&1
./bin/haskell-http-client-petstore.sh > /dev/null 2>&1
./bin/csharp-petstore.sh > /dev/null 2>&1
./bin/meta-codegen.sh > /dev/null 2>&1
./bin/utils/export_docs_generators.sh > /dev/null 2>&1
./bin/go-petstore.sh > /dev/null 2>&1
./bin/go-gin-petstore-server.sh > /dev/null 2>&1
declare -a scripts=("./bin/openapi3/ruby-client-petstore.sh"
"./bin/ruby-client-petstore.sh"
"./bin/java-petstore-all.sh"
"./bin/java-jaxrs-petstore-server-all.sh"
"./bin/openapi3/jaxrs-jersey-petstore.sh"
"./bin/spring-all-pestore.sh"
"./bin/kotlin-client-petstore.sh"
"./bin/kotlin-client-string.sh"
"./bin/kotlin-client-threetenbp.sh"
"./bin/kotlin-server-petstore.sh"
"./bin/mysql-schema-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-ze-ph-petstore-server.sh"
"./bin/openapi3/php-petstore.sh"
"./bin/typescript-angular-petstore-all.sh"
"./bin/typescript-fetch-petstore-all.sh"
"./bin/typescript-node-petstore-all.sh"
"./bin/typescript-inversify-petstore.sh"
"./bin/rust-server-petstore.sh"
"./bin/haskell-http-client-petstore.sh"
"./bin/csharp-petstore.sh"
"./bin/meta-codegen.sh"
"./bin/utils/export_docs_generators.sh"
"./bin/go-petstore.sh"
"./bin/go-gin-petstore-server.sh")
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
# Check:
if [ -n "$(git status --porcelain)" ]; then

View File

@@ -1,8 +1,26 @@
#release_chekcout.rb
#!/usr/bin/env ruby
#
# release_chekcout.rb
#
require 'rubygems'
require 'open-uri'
require 'net/http'
def check_npmjs
print "Checking npmjs... "
url = "https://www.npmjs.com/package/@openapitools/openapi-generator-cli?activeTab=versions"
open(url) do |f|
content = f.read
if !content.nil? && content.include?($version)
puts "[OK]"
else
puts "[ERROR]"
puts "> #{url} not yet updated with #{$version}"
end
end
end
def check_homebrew
print "Checking homebrew forumla ... "
@@ -184,6 +202,7 @@ $version = ARGV[0]
puts "Running checkout on OpenAPI Generator release #{$version}"
check_npmjs
check_homebrew
check_openapi_generator_jar
check_openapi_generator_cli_jar

View File

@@ -0,0 +1,28 @@
#!/bin/bash
#
# A script to test all generators to ensure there's no Java exception when running it with OAS 2.0, 3.0 fake petstore spec
#
SCRIPT="$0"
echo "# START SCRIPT: ${SCRIPT}"
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
for GENERATOR in $(java -jar ${executable} list --short | sed -e 's/,/\'$'\n''/g')
do
if eval java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/2.0/${GENERATOR} > /dev/null 2>&1; then
echo "[OAS 2.0] Executed ${GENERATOR} successfully!"
else
echo "ERROR: Failed to run ${GENERATOR}"
echo "java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/2.0/${GENERATOR}"
exit 1
fi
if eval java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/3.0/${GENERATOR} > /dev/null 2>&1; then
echo "[OAS 3.0] Executed ${GENERATOR} successfully!"
else
echo "ERROR: Failed to run ${GENERATOR}"
echo "java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/3.0/${GENERATOR}"
exit 1
fi
done

10
bin/windows/c-petstore.bat Executable file
View File

@@ -0,0 +1,10 @@
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
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g c -o samples\client\petstore\c
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g cpp-qt5 -o samples\client\petstore\cpp-qt5
set ags=generate -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% %ags%

View File

@@ -0,0 +1,10 @@
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 dukescript -o samples\client\petstore\dukescript
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
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
set ags=generate -t modules\openapi-generator\src\main\resources\graphql-server -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g graphql-server -o samples\server\petstore\graphql-server
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
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
set ags=generate -t modules\openapi-generator\src\main\resources\graphql-schema -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g graphql-schema -o samples\config\petstore\graphql-schema
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -7,5 +7,8 @@ call .\bin\windows\typescript-angular-v6-provided-in-root.bat
call .\bin\windows\typescript-angular-v6-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v6-not-provided-in-root.bat
call .\bin\windows\typescript-angular-v6-not-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v7-provided-in-root.bat
call .\bin\windows\typescript-angular-v7-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v7-not-provided-in-root.bat
call .\bin\windows\typescript-angular-v7-not-provided-in-root-with-npm.bat

View File

@@ -0,0 +1,10 @@
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
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l typescript-angular -c bin\typescript-angular-v7-petstore-not-provided-in-root-with-npm.json -o samples\client\petstore\typescript-angular-v7-not-provided-in-root\builds\with-npm -D providedInRoot=false --additional-properties ngVersion=7.0.0
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
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
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -l typescript-angular -o samples\client\petstore\typescript-angular-v7-not-provided-in-root\builds\default -D providedInRoot=false --additional-properties ngVersion=7.0.0
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,9 @@
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 -l typescript-angular -c bin/typescript-angular-v7-petstore-provided-in-root-with-npm.json -o samples\client\petstore\typescript-angular-v7-provided-in-root\builds\with-npm --additional-properties ngVersion=7.0.0
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,9 @@
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 -l typescript-angular -o samples\client\petstore\typescript-angular-v7-provided-in-root\builds\default --additional-properties ngVersion=7.0.0
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -17,7 +17,7 @@ CONFIG OPTIONS for clojure
name of the project (Default: generated from info.title or "openapi-clj-client")
projectDescription
description of the project (Default: using info.description or "Client library of <projectNname>")
description of the project (Default: using info.description or "Client library of <projectName>")
projectVersion
version of the project (Default: using info.version or "1.0.0")

View File

@@ -16,4 +16,7 @@ CONFIG OPTIONS for cpp-qt5-qhttpengine-server
cppNamespace
C++ namespace (convention: name::space::for::api). (Default: OpenAPI)
cppNamespace
C++ namespace (convention: name::space::for::api). (Default: OpenAPI)
Back to the [generators list](README.md)

View File

@@ -34,4 +34,7 @@ CONFIG OPTIONS for dart-jaguar
supportDart2
support dart2 (Default: true)
nullableFields
Is the null fields should be in the JSON payload
Back to the [generators list](README.md)

View File

@@ -9,4 +9,10 @@ CONFIG OPTIONS for elm
elmPrefixCustomTypeVariants
Prefix custom type variants (Default: false)
elmEnableCustomBasePaths
Enable setting the base path for each request (Default: false)
elmEnableHttpRequestTrackers
Enable adding a tracker to each http request (Default: false)
Back to the [generators list](README.md)

View File

@@ -19,6 +19,9 @@ CONFIG OPTIONS for kotlin-server
enumPropertyNaming
Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original' (Default: camelCase)
parcelizeModels
toggle "@Parcelize" for generated models
library
library template (sub-template) to use (Default: ktor)
ktor - ktor framework

View File

@@ -19,6 +19,9 @@ CONFIG OPTIONS for kotlin-spring
enumPropertyNaming
Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original' (Default: camelCase)
parcelizeModels
toggle "@Parcelize" for generated models
title
server title name or client service name (Default: OpenAPI Kotlin Spring)

View File

@@ -19,10 +19,18 @@ CONFIG OPTIONS for kotlin
enumPropertyNaming
Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original' (Default: camelCase)
parcelizeModels
toggle "@Parcelize" for generated models
dateLibrary
Option. Date library to use
string - String
java8 - Java 8 native JSR310
threetenbp - Threetenbp
collectionType
Option. Collection type to use
array - kotlin.Array
list - kotlin.collections.List
Back to the [generators list](README.md)

View File

@@ -5,6 +5,6 @@ CONFIG OPTIONS for rust-server
Rust crate name (convention: snake_case). (Default: openapi_client)
packageVersion
Rust crate version. (Default: 1.0.0)
Rust crate version.
Back to the [generators list](README.md)

View File

@@ -170,6 +170,9 @@ CONFIG OPTIONS for spring
hateoas
Use Spring HATEOAS library to allow adding HATEOAS links (Default: false)
returnSuccessCode
Generated server returns 2xx code (Default: false)
library
library template (sub-template) to use (Default: spring-boot)
spring-boot - Spring-boot Server application using the SpringFox integration.

View File

@@ -1,14 +1,25 @@
## Online OpenAPI generator
One can also generate API client or server using the online openapi-generator.
One can also generate API clients or server stubs using the online openapi-generator.
Here are the steps to run it locally:
Here are the public online services:
- latest stable version: http://api.openapi-generator.tech
- latest master: http://api-latest-master.openapi-generator.tech (updated with latest master every hour)
The server is sponsored by [Linode](https://www.linode.com/) [![Linode Logo](https://www.linode.com/media/images/logos/standard/light/linode-logo_standard_light_small.png)](https://www.linode.com/)
(These services are beta and do not have any guarantee on service level)
If you prefer to run the service locally, here are the steps:
```
mvn clean install
cd modules/openapi-generator-online
mvn spring-boot:run
```
:bulb: The online openapi-generator can be run via [Docker](https://github.com/OpenAPITools/openapi-generator#16---docker) as well.
For example, to generate Ruby API client, simply send the following HTTP request using curl:
```sh
curl -X POST -H "content-type:application/json" -d '{"openAPIUrl":"https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml"}' http://localhost:8080/api/gen/clients/ruby

View File

@@ -1,7 +1,11 @@
FROM java:8-jre-alpine
ADD target/openapi-generator-cli.jar /opt/openapi-generator-cli/openapi-generator-cli.jar
RUN apk add --no-cache bash
ENTRYPOINT ["java", "-jar", "/opt/openapi-generator-cli/openapi-generator-cli.jar"]
ADD target/openapi-generator-cli.jar /opt/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar
CMD ["help"]
COPY docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["help"]

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<version>3.3.2</version>
<version>4.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -32,6 +32,7 @@ import org.slf4j.LoggerFactory;
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
@@ -246,6 +247,11 @@ public class Generate implements Runnable {
}
if (isNotEmpty(spec)) {
if (!spec.matches("^http(s)?://.*") && !new File(spec).exists()) {
System.err.println("[error] The spec file is not found: " + spec);
System.err.println("[error] Check the path of the OpenAPI spec and try again.");
System.exit(1);
}
configurator.setInputSpec(spec);
}

View File

@@ -64,7 +64,7 @@ public class GenerateTest {
@Test
public void testRequiredArgs_ShortArgs() throws Exception {
setupAndRunTest("-i", "swagger.yaml", "-g", "java", "-o", "src/main/java", false, null);
setupAndRunTest("-i", "src/test/resources/swagger.yaml", "-g", "java", "-o", "src/main/java", false, null);
new FullVerifications() {
{
}
@@ -73,7 +73,7 @@ public class GenerateTest {
@Test
public void testRequiredArgs_LongArgs() throws Exception {
setupAndRunTest("--input-spec", "swagger.yaml", "--generator-name", "java", "--output",
setupAndRunTest("--input-spec", "src/test/resources/swagger.yaml", "--generator-name", "java", "--output",
"src/main/java", false, null);
new FullVerifications() {
{
@@ -220,7 +220,7 @@ public class GenerateTest {
@Test
public void testConfig() throws Exception {
setupAndRunTest("-i", "swagger.yaml", "-g", "java", "-o", "src/main/java", true,
setupAndRunTest("-i", "src/test/resources/swagger.yaml", "-g", "java", "-o", "src/main/java", true,
"config.json", "-c", "config.json");
new FullVerifications() {
@@ -228,7 +228,7 @@ public class GenerateTest {
}
};
setupAndRunTest("-i", "swagger.yaml", "-g", "java", "-o", "src/main/java", true,
setupAndRunTest("-i", "src/test/resources/swagger.yaml", "-g", "java", "-o", "src/main/java", true,
"config.json", "--config", "config.json");
new FullVerifications() {
@@ -570,7 +570,7 @@ public class GenerateTest {
}
private void setupAndRunGenericTest(String... additionalParameters) {
setupAndRunTest("-i", "swagger.yaml", "-g", "java", "-o", "src/main/java", false, null,
setupAndRunTest("-i", "src/test/resources/swagger.yaml", "-g", "java", "-o", "src/main/java", false, null,
additionalParameters);
}
}

View File

@@ -0,0 +1,109 @@
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View File

@@ -48,7 +48,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:3.3.2"
classpath "org.openapitools:openapi-generator-gradle-plugin:3.3.4"
}
}
@@ -278,6 +278,32 @@ in others being disabled. That is, OpenAPI Generator considers any one of these
For more control over generation of individual files, configure an ignore file and refer to it via `ignoreFileOverride`.
====
[NOTE]
====
When configuring `systemProperties` in order to perform selective generation you can disable generation of some parts by providing `"false"` value:
[source,groovy]
----
openApiGenerate {
// other settings omitted
systemProperties = [
modelDocs: "false",
apis: "false"
]
}
----
When enabling generation of only specific parts you either have to provide CSV list of what you particularly are generating or provide an empty string `""` to generate everything. If you provide `"true"` it will be treated as a specific name of model or api you want to generate.
[source,groovy]
----
openApiGenerate {
// other settings omitted
systemProperties = [
apis: "",
models: "User,Pet"
]
}
----
====
=== openApiValidate
.Options

View File

@@ -0,0 +1,131 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.invoke
import org.openapitools.generator.gradle.plugin.extensions.OpenApiGeneratorGenerateExtension
import org.openapitools.generator.gradle.plugin.extensions.OpenApiGeneratorMetaExtension
import org.openapitools.generator.gradle.plugin.extensions.OpenApiGeneratorValidateExtension
import org.openapitools.generator.gradle.plugin.tasks.GenerateTask
import org.openapitools.generator.gradle.plugin.tasks.GeneratorsTask
import org.openapitools.generator.gradle.plugin.tasks.MetaTask
import org.openapitools.generator.gradle.plugin.tasks.ValidateTask
/**
* A plugin providing common Open API Generator use cases.
*
* @author Jim Schubert
*/
@Suppress("unused")
class OpenApiGeneratorPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.run {
val meta = extensions.create(
"openApiMeta",
OpenApiGeneratorMetaExtension::class.java,
project
)
val validate = extensions.create(
"openApiValidate",
OpenApiGeneratorValidateExtension::class.java,
project
)
val generate = extensions.create(
"openApiGenerate",
OpenApiGeneratorGenerateExtension::class.java,
project
)
generate.outputDir.set("$buildDir/generate-resources/main")
tasks {
"openApiGenerators"(GeneratorsTask::class) {
group = pluginGroup
description = "Lists generators available via Open API Generators."
}
"openApiMeta"(MetaTask::class) {
group = pluginGroup
description = "Generates a new generator to be consumed via Open API Generator."
generatorName.set(meta.generatorName)
packageName.set(meta.packageName)
outputFolder.set(meta.outputFolder)
}
"openApiValidate"(ValidateTask::class) {
group = pluginGroup
description = "Validates an Open API 2.0 or 3.x specification document."
inputSpec.set(validate.inputSpec)
}
"openApiGenerate"(GenerateTask::class) {
group = pluginGroup
description = "Generate code via Open API Tools Generator for Open API 2.0 or 3.x specification documents."
verbose.set(generate.verbose)
validateSpec.set(generate.validateSpec)
generatorName.set(generate.generatorName)
outputDir.set(generate.outputDir)
inputSpec.set(generate.inputSpec)
templateDir.set(generate.templateDir)
auth.set(generate.auth)
systemProperties.set(generate.systemProperties)
configFile.set(generate.configFile)
skipOverwrite.set(generate.skipOverwrite)
apiPackage.set(generate.apiPackage)
modelPackage.set(generate.modelPackage)
modelNamePrefix.set(generate.modelNamePrefix)
modelNameSuffix.set(generate.modelNameSuffix)
instantiationTypes.set(generate.instantiationTypes)
typeMappings.set(generate.typeMappings)
additionalProperties.set(generate.additionalProperties)
languageSpecificPrimitives.set(generate.languageSpecificPrimitives)
importMappings.set(generate.importMappings)
invokerPackage.set(generate.invokerPackage)
groupId.set(generate.groupId)
id.set(generate.id)
version.set(generate.version)
library.set(generate.library)
gitUserId.set(generate.gitUserId)
gitRepoId.set(generate.gitRepoId)
releaseNote.set(generate.releaseNote)
httpUserAgent.set(generate.httpUserAgent)
reservedWordsMappings.set(generate.reservedWordsMappings)
ignoreFileOverride.set(generate.ignoreFileOverride)
removeOperationIdPrefix.set(generate.removeOperationIdPrefix)
apiFilesConstrainedTo.set(generate.apiFilesConstrainedTo)
modelFilesConstrainedTo.set(generate.modelFilesConstrainedTo)
supportingFilesConstrainedTo.set(generate.supportingFilesConstrainedTo)
generateModelTests.set(generate.generateModelTests)
generateModelDocumentation.set(generate.generateModelDocumentation)
generateApiTests.set(generate.generateApiTests)
generateApiDocumentation.set(generate.generateApiDocumentation)
withXml.set(generate.withXml)
configOptions.set(generate.configOptions)
}
}
}
}
companion object {
const val pluginGroup = "OpenAPI Tools"
}
}

View File

@@ -0,0 +1,286 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin.extensions
import org.gradle.api.Project
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.property
/**
* Gradle project level extension object definition for the generate task
*
* @author Jim Schubert
*/
open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* The verbosity of generation
*/
val verbose = project.objects.property<Boolean>()
/**
* Whether or not an input specification should be validated upon generation.
*/
val validateSpec = project.objects.property<Boolean>()
/**
* The name of the generator which will handle codegen. (see "openApiGenerators" task)
*/
val generatorName = project.objects.property<String>()
/**
* The output target directory into which code will be generated.
*/
val outputDir = project.objects.property<String>()
/**
* The Open API 2.0/3.x specification location.
*/
val inputSpec = project.objects.property<String>()
/**
* The template directory holding a custom template.
*/
val templateDir = project.objects.property<String?>()
/**
* Adds authorization headers when fetching the OpenAPI definitions remotely.
* Pass in a URL-encoded string of name:header with a comma separating multiple values
*/
val auth = project.objects.property<String>()
/**
* Sets specified system properties.
*/
val systemProperties = project.objects.property<Map<String, String>>()
/**
* Path to json configuration file.
* File content should be in a json format { "optionKey":"optionValue", "optionKey1":"optionValue1"...}
* Supported options can be different for each language. Run config-help -g {generator name} command for language specific config options.
*/
val configFile = project.objects.property<String>()
/**
* Specifies if the existing files should be overwritten during the generation.
*/
val skipOverwrite = project.objects.property<Boolean?>()
/**
* Package for generated api classes
*/
val apiPackage = project.objects.property<String>()
/**
* Package for generated models
*/
val modelPackage = project.objects.property<String>()
/**
* Prefix that will be prepended to all model names. Default is the empty string.
*/
val modelNamePrefix = project.objects.property<String>()
/**
* Suffix that will be appended to all model names. Default is the empty string.
*/
val modelNameSuffix = project.objects.property<String>()
/**
* Sets instantiation type mappings.
*/
val instantiationTypes = project.objects.property<Map<String, String>>()
/**
* Sets mappings between OpenAPI spec types and generated code types.
*/
val typeMappings = project.objects.property<Map<String, String>>()
/**
* Sets additional properties that can be referenced by the mustache templates.
*/
val additionalProperties = 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.
*/
val languageSpecificPrimitives = project.objects.listProperty<String>()
/**
* Specifies mappings between a given class and the import that should be used for that class.
*/
val importMappings = project.objects.property<Map<String, String>>()
/**
* Root package for generated code.
*/
val invokerPackage = project.objects.property<String>()
/**
* GroupId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
val groupId = project.objects.property<String>()
/**
* ArtifactId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
val id = project.objects.property<String>()
/**
* Artifact version in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
val version = project.objects.property<String>()
/**
* Reference the library template (sub-template) of a generator.
*/
val library = project.objects.property<String?>()
/**
* Git user ID, e.g. openapitools.
*/
val gitUserId = project.objects.property<String?>()
/**
* Git repo ID, e.g. openapi-generator.
*/
val gitRepoId = project.objects.property<String?>()
/**
* Release note, default to 'Minor update'.
*/
val releaseNote = project.objects.property<String?>()
/**
* HTTP user agent, e.g. codegen_csharp_api_client, default to 'OpenAPI-Generator/{packageVersion}}/{language}'
*/
val httpUserAgent = project.objects.property<String?>()
/**
* Specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used.
*/
val reservedWordsMappings = project.objects.property<Map<String, String>>()
/**
* Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation.
*/
val ignoreFileOverride = project.objects.property<String?>()
/**
* Remove prefix of operationId, e.g. config_getId => getId
*/
val removeOperationIdPrefix = project.objects.property<Boolean?>()
/**
* Defines which API-related files should be generated. This allows you to create a subset of generated files (or none at all).
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
val apiFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines which model-related files should be generated. This allows you to create a subset of generated files (or none at all).
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
val modelFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines which supporting files should be generated. This allows you to create a subset of generated files (or none at all).
*
* Supporting files are those related to projects/frameworks which may be modified
* by consumers.
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
val supportingFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines whether or not model-related _test_ files should be generated.
*
* This option enables/disables generation of ALL model-related _test_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
val generateModelTests = project.objects.property<Boolean>()
/**
* Defines whether or not model-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL model-related _documentation_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
val generateModelDocumentation = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _test_ files should be generated.
*
* This option enables/disables generation of ALL api-related _test_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
val generateApiTests = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL api-related _documentation_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
val generateApiDocumentation = project.objects.property<Boolean>()
/**
* A special-case setting which configures some generators with XML support. In some cases,
* this forces json OR xml, so the default here is false.
*/
val withXml = project.objects.property<Boolean>()
/**
* A map of options specific to a generator.
*/
val configOptions = project.objects.property<Map<String, String>>()
init {
applyDefaults()
}
@Suppress("MemberVisibilityCanBePrivate")
fun applyDefaults(){
releaseNote.set("Minor update")
modelNamePrefix.set("")
modelNameSuffix.set("")
generateModelTests.set(true)
generateModelDocumentation.set(true)
generateApiTests.set(true)
generateApiDocumentation.set(true)
withXml.set(false)
configOptions.set(mapOf())
validateSpec.set(true)
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin.extensions
import org.gradle.api.Project
import org.gradle.kotlin.dsl.property
/**
* Gradle project level extension object definition for the meta-generator task
*
* @author Jim Schubert
*/
open class OpenApiGeneratorMetaExtension(project: Project) {
/**
* The human-readable generator name of the newly created template generator.
*/
val generatorName = project.objects.property<String>()
/**
* The packageName generatorName to put the main class into (defaults to org.openapitools.codegen)
*/
val packageName = project.objects.property<String>()
/**
* Where to write the generated files (current dir by default).
*/
val outputFolder = project.objects.property<String>()
init {
generatorName.set("default")
packageName.set("org.openapitools.codegen")
outputFolder.set("")
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin.extensions
import org.gradle.api.Project
import org.gradle.kotlin.dsl.property
/**
* Gradle project level extension object definition for the generators task
*
* @author Jim Schubert
*/
open class OpenApiGeneratorValidateExtension(project: Project) {
/**
* The input specification to validate. Supports all formats supported by the Parser.
*/
val inputSpec = project.objects.property<String>()
}

View File

@@ -0,0 +1,554 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Internal
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.property
import org.openapitools.codegen.CodegenConstants
import org.openapitools.codegen.DefaultGenerator
import org.openapitools.codegen.config.CodegenConfigurator
/**
* A task which generates the desired code.
*
* Example (CLI):
*
* ./gradlew -q openApiGenerate
*
* @author Jim Schubert
*/
open class GenerateTask : DefaultTask() {
/**
* The verbosity of generation
*/
@get:Internal
val verbose = project.objects.property<Boolean>()
/**
* Whether or not an input specification should be validated upon generation.
*/
@get:Internal
val validateSpec = project.objects.property<Boolean>()
/**
* The name of the generator which will handle codegen. (see "openApiGenerators" task)
*/
@get:Internal
val generatorName = project.objects.property<String>()
/**
* The output target directory into which code will be generated.
*/
@get:Internal
val outputDir = project.objects.property<String>()
/**
* The Open API 2.0/3.x specification location.
*/
@get:Internal
val inputSpec = project.objects.property<String>()
/**
* The template directory holding a custom template.
*/
@get:Internal
val templateDir = project.objects.property<String?>()
/**
* Adds authorization headers when fetching the OpenAPI definitions remotely.
* Pass in a URL-encoded string of name:header with a comma separating multiple values
*/
@get:Internal
val auth = project.objects.property<String>()
/**
* Sets specified system properties.
*/
@get:Internal
val systemProperties = project.objects.property<Map<String, String>>()
/**
* Path to json configuration file.
* File content should be in a json format { "optionKey":"optionValue", "optionKey1":"optionValue1"...}
* Supported options can be different for each language. Run config-help -g {generator name} command for language specific config options.
*/
@get:Internal
val configFile = project.objects.property<String>()
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@get:Internal
val skipOverwrite = project.objects.property<Boolean?>()
/**
* Package for generated api classes
*/
@get:Internal
val apiPackage = project.objects.property<String>()
/**
* Package for generated models
*/
@get:Internal
val modelPackage = project.objects.property<String>()
/**
* Prefix that will be prepended to all model names. Default is the empty string.
*/
@get:Internal
val modelNamePrefix = project.objects.property<String>()
/**
* Suffix that will be appended to all model names. Default is the empty string.
*/
@get:Internal
val modelNameSuffix = project.objects.property<String>()
/**
* Sets instantiation type mappings.
*/
@get:Internal
val instantiationTypes = project.objects.property<Map<String, String>>()
/**
* Sets mappings between OpenAPI spec types and generated code types.
*/
@get:Internal
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.property<Map<String, String>>()
/**
* Specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double.
*/
@get:Internal
val languageSpecificPrimitives = project.objects.listProperty<String>()
/**
* Specifies mappings between a given class and the import that should be used for that class.
*/
@get:Internal
val importMappings = project.objects.property<Map<String, String>>()
/**
* Root package for generated code.
*/
@get:Internal
val invokerPackage = project.objects.property<String>()
/**
* GroupId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
@get:Internal
val groupId = project.objects.property<String>()
/**
* ArtifactId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
@get:Internal
val id = project.objects.property<String>()
/**
* Artifact version in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
@get:Internal
val version = project.objects.property<String>()
/**
* Reference the library template (sub-template) of a generator.
*/
@get:Internal
val library = project.objects.property<String?>()
/**
* Git user ID, e.g. openapitools.
*/
@get:Internal
val gitUserId = project.objects.property<String?>()
/**
* Git repo ID, e.g. openapi-generator.
*/
@get:Internal
val gitRepoId = project.objects.property<String?>()
/**
* Release note, default to 'Minor update'.
*/
@get:Internal
val releaseNote = project.objects.property<String?>()
/**
* HTTP user agent, e.g. codegen_csharp_api_client, default to 'OpenAPI-Generator/{packageVersion}}/{language}'
*/
@get:Internal
val httpUserAgent = project.objects.property<String?>()
/**
* Specifies how a reserved name should be escaped to.
*/
@get:Internal
val reservedWordsMappings = project.objects.property<Map<String, String>>()
/**
* Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation.
*/
@get:Internal
val ignoreFileOverride = project.objects.property<String?>()
/**
* Remove prefix of operationId, e.g. config_getId => getId
*/
@get:Internal
val removeOperationIdPrefix = project.objects.property<Boolean?>()
/**
* Defines which API-related files should be generated. This allows you to create a subset of generated files (or none at all).
*
* This option enables/disables generation of ALL api-related files.
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
@get:Internal
val apiFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines which model-related files should be generated. This allows you to create a subset of generated files (or none at all).
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
@get:Internal
val modelFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines which supporting files should be generated. This allows you to create a subset of generated files (or none at all).
*
* Supporting files are those related to projects/frameworks which may be modified
* by consumers.
*
* NOTE: Configuring any one of [apiFilesConstrainedTo], [modelFilesConstrainedTo], or [supportingFilesConstrainedTo] results
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
@get:Internal
val supportingFilesConstrainedTo = project.objects.listProperty<String>()
/**
* Defines whether or not model-related _test_ files should be generated.
*
* This option enables/disables generation of ALL model-related _test_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@get:Internal
val generateModelTests = project.objects.property<Boolean>()
/**
* Defines whether or not model-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL model-related _documentation_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@get:Internal
val generateModelDocumentation = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _test_ files should be generated.
*
* This option enables/disables generation of ALL api-related _test_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@get:Internal
val generateApiTests = project.objects.property<Boolean>()
/**
* Defines whether or not api-related _documentation_ files should be generated.
*
* This option enables/disables generation of ALL api-related _documentation_ files.
*
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@get:Internal
val generateApiDocumentation = project.objects.property<Boolean>()
/**
* A special-case setting which configures some generators with XML support. In some cases,
* this forces json OR xml, so the default here is false.
*/
@get:Internal
val withXml = project.objects.property<Boolean>()
/**
* A dynamic map of options specific to a generator.
*/
@get:Internal
val configOptions = project.objects.property<Map<String, String>>()
private val originalEnvironmentVariables = mutableMapOf<String, String?>()
private fun <T : Any?> Property<T>.ifNotEmpty(block: Property<T>.(T) -> Unit) {
if (isPresent) {
val item: T? = get()
if (item != null) {
when (get()) {
is String -> if ((get() as String).isNotEmpty()) {
block(get())
}
is String? -> if (true == (get() as String?)?.isNotEmpty()) {
block(get())
}
else -> block(get())
}
}
}
}
@Suppress("unused")
@TaskAction
fun doWork() {
val configurator: CodegenConfigurator = if (configFile.isPresent) {
CodegenConfigurator.fromFile(configFile.get())
} else CodegenConfigurator()
try {
if (systemProperties.isPresent) {
systemProperties.get().forEach { (key, value) ->
// System.setProperty returns the original value for a key, or null.
// Cache the original value or null…we will late put the properties back in their original state.
originalEnvironmentVariables[key] = System.setProperty(key, value)
configurator.addSystemProperty(key, value)
}
}
if (supportingFilesConstrainedTo.isPresent && supportingFilesConstrainedTo.get().isNotEmpty()) {
System.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesConstrainedTo.get().joinToString(","))
} else {
System.clearProperty(CodegenConstants.SUPPORTING_FILES)
}
if (modelFilesConstrainedTo.isPresent && modelFilesConstrainedTo.get().isNotEmpty()) {
System.setProperty(CodegenConstants.MODELS, modelFilesConstrainedTo.get().joinToString(","))
} else {
System.clearProperty(CodegenConstants.MODELS)
}
if (apiFilesConstrainedTo.isPresent && apiFilesConstrainedTo.get().isNotEmpty()) {
System.setProperty(CodegenConstants.APIS, apiFilesConstrainedTo.get().joinToString(","))
} else {
System.clearProperty(CodegenConstants.APIS)
}
System.setProperty(CodegenConstants.API_DOCS, generateApiDocumentation.get().toString())
System.setProperty(CodegenConstants.MODEL_DOCS, generateModelDocumentation.get().toString())
System.setProperty(CodegenConstants.MODEL_TESTS, generateModelTests.get().toString())
System.setProperty(CodegenConstants.API_TESTS, generateApiTests.get().toString())
System.setProperty(CodegenConstants.WITH_XML, withXml.get().toString())
// now override with any specified parameters
verbose.ifNotEmpty { value ->
configurator.isVerbose = value
}
validateSpec.ifNotEmpty { value ->
configurator.isValidateSpec = value
}
skipOverwrite.ifNotEmpty { value ->
configurator.isSkipOverwrite = value ?: false
}
inputSpec.ifNotEmpty { value ->
configurator.inputSpec = value
}
generatorName.ifNotEmpty { value ->
configurator.generatorName = value
}
outputDir.ifNotEmpty { value ->
configurator.outputDir = value
}
auth.ifNotEmpty { value ->
configurator.auth = value
}
templateDir.ifNotEmpty { value ->
configurator.templateDir = value
}
apiPackage.ifNotEmpty { value ->
configurator.apiPackage = value
}
modelPackage.ifNotEmpty { value ->
configurator.modelPackage = value
}
modelNamePrefix.ifNotEmpty { value ->
configurator.modelNamePrefix = value
}
modelNameSuffix.ifNotEmpty { value ->
configurator.modelNameSuffix = value
}
invokerPackage.ifNotEmpty { value ->
configurator.invokerPackage = value
}
groupId.ifNotEmpty { value ->
configurator.groupId = value
}
id.ifNotEmpty { value ->
configurator.artifactId = value
}
version.ifNotEmpty { value ->
configurator.artifactVersion = value
}
library.ifNotEmpty { value ->
configurator.library = value
}
gitUserId.ifNotEmpty { value ->
configurator.gitUserId = value
}
gitRepoId.ifNotEmpty { value ->
configurator.gitRepoId = value
}
releaseNote.ifNotEmpty { value ->
configurator.releaseNote = value
}
httpUserAgent.ifNotEmpty { value ->
configurator.httpUserAgent = value
}
ignoreFileOverride.ifNotEmpty { value ->
configurator.ignoreFileOverride = value
}
removeOperationIdPrefix.ifNotEmpty { value ->
configurator.removeOperationIdPrefix = value!!
}
if (systemProperties.isPresent) {
systemProperties.get().forEach { entry ->
configurator.addSystemProperty(entry.key, entry.value)
}
}
if (instantiationTypes.isPresent) {
instantiationTypes.get().forEach { entry ->
configurator.addInstantiationType(entry.key, entry.value)
}
}
if (importMappings.isPresent) {
importMappings.get().forEach { entry ->
configurator.addImportMapping(entry.key, entry.value)
}
}
if (typeMappings.isPresent) {
typeMappings.get().forEach { entry ->
configurator.addTypeMapping(entry.key, entry.value)
}
}
if (additionalProperties.isPresent) {
additionalProperties.get().forEach { entry ->
configurator.addAdditionalProperty(entry.key, entry.value)
}
}
if (languageSpecificPrimitives.isPresent) {
languageSpecificPrimitives.get().forEach {
configurator.addLanguageSpecificPrimitive(it)
}
}
if (reservedWordsMappings.isPresent) {
reservedWordsMappings.get().forEach { entry ->
configurator.addAdditionalReservedWordMapping(entry.key, entry.value)
}
}
val clientOptInput = configurator.toClientOptInput()
val codgenConfig = clientOptInput.config
if (configOptions.isPresent) {
val userSpecifiedConfigOptions = configOptions.get()
codgenConfig.cliOptions().forEach {
if (userSpecifiedConfigOptions.containsKey(it.opt)) {
clientOptInput.config.additionalProperties()[it.opt] = userSpecifiedConfigOptions[it.opt]
}
}
}
try {
val out = services.get(StyledTextOutputFactory::class.java).create("openapi")
out.withStyle(StyledTextOutput.Style.Success)
DefaultGenerator().opts(clientOptInput).generate()
out.println("Successfully generated code to ${configurator.outputDir}")
} catch (e: RuntimeException) {
throw GradleException("Code generation failed.", e)
}
} finally {
// Reset all modified system properties back to their original state
originalEnvironmentVariables.forEach {
when {
it.value == null -> System.clearProperty(it.key)
else -> System.setProperty(it.key, it.value)
}
}
originalEnvironmentVariables.clear()
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.internal.logging.text.StyledTextOutput
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.openapitools.codegen.CodegenConfigLoader
import org.openapitools.codegen.CodegenType
/**
* A task which lists out the generators available in OpenAPI Generator
*
* Example (CLI):
*
* ./gradlew -q openApiGenerators
*
* @author Jim Schubert
*/
open class GeneratorsTask : DefaultTask() {
@Suppress("unused")
@TaskAction
fun doWork() {
val generators = CodegenConfigLoader.getAll()
val out = services.get(StyledTextOutputFactory::class.java).create("openapi")
StringBuilder().apply {
val types = CodegenType.values()
append("The following generators are available:")
append(System.lineSeparator())
append(System.lineSeparator())
for (type in types) {
append(type.name).append(" generators:")
append(System.lineSeparator())
generators.filter { it.tag == type }
.sortedBy { it.name }
.forEach({ generator ->
append(" - ")
append(generator.name)
append(System.lineSeparator())
})
append(System.lineSeparator())
append(System.lineSeparator())
}
out.withStyle(StyledTextOutput.Style.Success)
out.formatln("%s%n", toString())
}
}
}

View File

@@ -0,0 +1,132 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin.tasks
import com.samskivert.mustache.Mustache
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.Internal
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.property
import org.openapitools.codegen.CodegenConfig
import org.openapitools.codegen.CodegenConstants
import org.openapitools.codegen.DefaultGenerator
import org.openapitools.codegen.SupportingFile
import java.io.File
import java.io.IOException
import java.nio.charset.Charset
/**
* A task which generates a new generator (meta). Useful for redistributable generator packages.
*
* @author Jim Schubert
*/
open class MetaTask : DefaultTask() {
@get:Internal
val generatorName = project.objects.property<String>()
@get:Internal
val packageName = project.objects.property<String>()
@get:Internal
val outputFolder = project.objects.property<String>()
@Suppress("unused")
@TaskAction
fun doWork() {
val packageToPath = packageName.get().replace(".", File.separator)
val dir = File(outputFolder.get())
val klass = "${generatorName.get().titleCasedTextOnly()}Generator"
val templateResourceDir = generatorName.get().hyphenatedTextOnly()
val out = services.get(StyledTextOutputFactory::class.java).create("openapi")
out.withStyle(StyledTextOutput.Style.Info)
logger.debug("package: {}", packageName.get())
logger.debug("dir: {}", dir.absolutePath)
logger.debug("generator class: {}", klass)
val supportingFiles = listOf(
SupportingFile("pom.mustache", "", "pom.xml"),
SupportingFile("generatorClass.mustache", dir("src", "main", "java", packageToPath), "$klass.java"),
SupportingFile("README.mustache", "", "README.md"),
SupportingFile("api.template", dir("src", "main", "resources", templateResourceDir), "api.mustache"),
SupportingFile("model.template", dir("src", "main", "resources", templateResourceDir), "model.mustache"),
SupportingFile("myFile.template", dir("src", "main", "resources", templateResourceDir), "myFile.mustache"),
SupportingFile("services.mustache", dir("src", "main", "resources", "META-INF", "services"), CodegenConfig::class.java.canonicalName))
val currentVersion = CodegenConstants::class.java.`package`.implementationVersion
val data = mapOf("generatorPackage" to packageToPath,
"generatorClass" to klass,
"name" to templateResourceDir,
"fullyQualifiedGeneratorClass" to "${packageName.get()}.$klass",
"openapiGeneratorVersion" to currentVersion)
val generator = DefaultGenerator()
supportingFiles.map {
try {
val destinationFolder = File(File(dir.absolutePath), it.folder)
destinationFolder.mkdirs()
val outputFile = File(destinationFolder, it.destinationFilename)
val template = generator.readTemplate(File("codegen", it.templateFile).path)
var formatted = template
if (it.templateFile.endsWith(".mustache")) {
formatted = Mustache.compiler()
.withLoader(loader(generator))
.defaultValue("")
.compile(template).execute(data)
}
outputFile.writeText(formatted, Charset.forName("UTF8"))
out.formatln("Wrote file to %s", outputFile.absolutePath)
// TODO: register outputs
// return outputFile
} catch (e: IOException) {
logger.error(e.message)
throw GradleException("Can't generate project", e)
}
}
out.withStyle(StyledTextOutput.Style.Success)
out.formatln("Created generator %s", klass)
}
private fun loader(generator: DefaultGenerator): Mustache.TemplateLoader {
return Mustache.TemplateLoader { name ->
generator.getTemplateReader("codegen${File.separator}$name.mustache")
}
}
private fun String.titleCasedTextOnly(): String =
this.split(Regex("[^a-zA-Z0-9]")).joinToString(separator = "", transform = String::capitalize)
private fun String.hyphenatedTextOnly(): String =
this.split(Regex("[^a-zA-Z0-9]")).joinToString(separator = "-", transform = String::toLowerCase)
private fun dir(vararg parts: String): String =
parts.joinToString(separator = File.separator)
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.generator.gradle.plugin.tasks
import io.swagger.parser.OpenAPIParser
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.internal.logging.text.StyledTextOutput
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.gradle.kotlin.dsl.property
/**
* A generator which validates an Open API spec. This task outputs a list of validation issues and errors.
*
* Example:
* cli:
*
* ./gradlew openApiValidate --input=/path/to/file
*
* build.gradle:
*
* openApiMeta {
* inputSpec = "path/to/spec.yaml"
* }
*
* @author Jim Schubert
*/
open class ValidateTask : DefaultTask() {
@get:Internal
var inputSpec = project.objects.property<String>()
@Suppress("unused")
@get:Internal
@set:Option(option = "input", description = "The input specification.")
var input: String? = null
set(value) {
inputSpec.set(value)
}
@Suppress("unused")
@TaskAction
fun doWork() {
val spec = inputSpec.get()
logger.quiet("Validating spec $spec")
val result = OpenAPIParser().readLocation(spec, null, null)
val messages = result.messages.toSet()
val out = services.get(StyledTextOutputFactory::class.java).create("openapi")
if (messages.isNotEmpty()) {
out.withStyle(StyledTextOutput.Style.Error)
out.println("\nSpec is invalid.\nIssues:\n")
messages.forEach {
out.withStyle(StyledTextOutput.Style.Error)
out.println("\t$it\n")
}
throw GradleException("Validation failed.")
} else {
out.withStyle(StyledTextOutput.Style.Success)
out.println("Spec is valid.")
}
}
}

View File

@@ -0,0 +1,71 @@
package org.openapitools.generator.gradle.plugin
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.testng.annotations.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class GenerateTaskDslTest : TestBase() {
override var temp: File = createTempDir(javaClass.simpleName)
private val defaultBuildGradle = """
plugins {
id 'org.openapi.generator'
}
openApiGenerate {
generatorName = "kotlin"
inputSpec = file("spec.yaml").absolutePath
outputDir = file("build/kotlin").absolutePath
apiPackage = "org.openapitools.example.api"
invokerPackage = "org.openapitools.example.invoker"
modelPackage = "org.openapitools.example.model"
configOptions = [
dateLibrary: "java8"
]
}
""".trimIndent()
@Test
fun `openApiGenerate should create an expected file structure from DSL config`() {
// Arrange
val projectFiles = mapOf(
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0.yaml")
)
withProject(defaultBuildGradle, projectFiles)
// Act
val result = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate")
.withPluginClasspath()
.build()
// Assert
assertTrue(result.output.contains("Successfully generated code to"), "User friendly generate notice is missing.")
listOf(
"build/kotlin/.openapi-generator-ignore",
"build/kotlin/docs/PetsApi.md",
"build/kotlin/docs/Pets.md",
"build/kotlin/docs/Error.md",
"build/kotlin/docs/Pet.md",
"build/kotlin/README.md",
"build/kotlin/build.gradle",
"build/kotlin/.openapi-generator/VERSION",
"build/kotlin/settings.gradle",
"build/kotlin/src/main/kotlin/org/openapitools/example/model/Pets.kt",
"build/kotlin/src/main/kotlin/org/openapitools/example/model/Pet.kt",
"build/kotlin/src/main/kotlin/org/openapitools/example/model/Error.kt",
"build/kotlin/src/main/kotlin/org/openapitools/example/api/PetsApi.kt",
"build/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt"
).map {
val f = File(temp, it)
assertTrue(f.exists() && f.isFile, "An expected file was not generated when invoking the generation.")
}
assertEquals(TaskOutcome.SUCCESS, result.task(":openApiGenerate")?.outcome,
"Expected a successful run, but found ${result.task(":openApiGenerate")?.outcome}")
}
}

View File

@@ -0,0 +1,38 @@
package org.openapitools.generator.gradle.plugin
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.testng.annotations.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class GeneratorsTaskDslTest : TestBase() {
override var temp: File = createTempDir(javaClass.simpleName)
@Test
fun `openApiGenerators should list generators available to the user`() {
// Arrange
withProject("""
| plugins {
| id 'org.openapi.generator'
| }
""".trimMargin())
// Act
val result = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerators")
.withPluginClasspath()
.build()
// Assert
assertTrue(result.output.contains("The following generators are available:"), "User friendly generator notice is missing.")
assertTrue(result.output.contains("CLIENT generators:"), "Expected client generator header is missing.")
assertTrue(result.output.contains("android"), "Spot-checking listed client generators is missing a client generator.")
assertTrue(result.output.contains("SERVER generators:"), "Expected server generator header is missing.")
assertTrue(result.output.contains("kotlin-server"), "Spot-checking listed server generators is missing a server generator.")
assertEquals(TaskOutcome.SUCCESS, result.task(":openApiGenerators")?.outcome,
"Expected a successful run, but found ${result.task(":openApiGenerators")?.outcome}")
}
}

View File

@@ -0,0 +1,58 @@
package org.openapitools.generator.gradle.plugin
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.testng.annotations.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class MetaTaskDslTest : TestBase() {
override var temp: File = createTempDir(javaClass.simpleName)
@Test
fun `openApiMeta should generate desired project contents`() {
// Arrange
val buildDirReplacement = "\$buildDir/meta"
withProject("""
| plugins {
| id 'org.openapi.generator'
| }
|
| openApiMeta {
| generatorName = "Sample"
| packageName = "org.openapitools.example"
| outputFolder = "$buildDirReplacement".toString()
| }
""".trimMargin())
// Act
val result = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiMeta")
.withPluginClasspath()
.build()
// Assert
assertTrue(result.output.contains("Wrote file to"), "User friendly write notice is missing.")
// To avoid any OS-specific output causing issues with our stdout comparisons, only compare on expected filenames.
listOf(
"SampleGenerator.java",
"README.md",
"api.mustache",
"model.mustache",
"myFile.mustache",
"org.openapitools.codegen.CodegenConfig",
"pom.xml"
).map {
assertTrue(result.output.contains(it), "Expected $it to be listed in gradle stdout.")
}
assertEquals(
TaskOutcome.SUCCESS,
result.task(":openApiMeta")?.outcome,
"Expected a successful run, but found ${result.task(":openApiMeta")?.outcome}"
)
}
}

View File

@@ -0,0 +1,34 @@
package org.openapitools.generator.gradle.plugin
import org.testng.annotations.AfterMethod
import org.testng.annotations.BeforeMethod
import java.io.File
import java.io.InputStream
abstract class TestBase {
protected open lateinit var temp: File
@BeforeMethod
protected fun before() {
temp = createTempDir(javaClass.simpleName)
temp.deleteOnExit()
}
@AfterMethod
protected fun after(){
temp.deleteRecursively()
}
protected fun withProject(
buildContents: String,
projectFiles: Map<String, InputStream> = mapOf()
) {
val buildFile = File(temp,"build.gradle")
buildFile.writeText(buildContents)
projectFiles.forEach { entry ->
val target = File(temp, entry.key)
entry.value.copyTo(target.outputStream())
}
}
}

View File

@@ -0,0 +1,99 @@
package org.openapitools.generator.gradle.plugin
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome.FAILED
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.testng.annotations.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ValidateTaskDslTest : TestBase() {
override var temp: File = createTempDir(javaClass.simpleName)
@Test
fun `openApiValidate should fail on non-file spec`() {
// Arrange
withProject("""
| plugins {
| id 'org.openapi.generator'
| }
|
| openApiValidate {
| inputSpec = "some_location"
| }
""".trimMargin())
// Act
val result = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiValidate")
.withPluginClasspath()
.buildAndFail()
// Assert
assertTrue(result.output.contains("unable to read location `some_location`"), "Unexpected/no message presented to the user for a spec pointing to an invalid URI.")
assertEquals(FAILED, result.task(":openApiValidate")?.outcome,
"Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}")
}
@Test
fun `openApiValidate should succeed on valid spec`() {
// Arrange
val projectFiles = mapOf(
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0.yaml")
)
withProject("""
| plugins {
| id 'org.openapi.generator'
| }
|
| openApiValidate {
| inputSpec = file("spec.yaml").absolutePath
| }
""".trimMargin(), projectFiles)
// Act
val result = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiValidate")
.withPluginClasspath()
.build()
// Assert
assertTrue(result.output.contains("Spec is valid."), "Unexpected/no message presented to the user for a valid spec.")
assertEquals(SUCCESS, result.task(":openApiValidate")?.outcome,
"Expected a successful run, but found ${result.task(":openApiValidate")?.outcome}")
}
@Test
fun `openApiValidate should fail on invalid spec`() {
// Arrange
val projectFiles = mapOf(
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0-invalid.yaml")
)
withProject("""
| plugins {
| id 'org.openapi.generator'
| }
|
| openApiValidate {
| inputSpec = file('spec.yaml').absolutePath
| }
""".trimMargin(), projectFiles)
// Act
val result = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiValidate")
.withPluginClasspath()
.buildAndFail()
// Assert
assertTrue(result.output.contains("Spec is invalid."), "Unexpected/no message presented to the user for an invalid spec.")
assertEquals(FAILED, result.task(":openApiValidate")?.outcome,
"Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}")
}
}

View File

@@ -0,0 +1,103 @@
openapi: "3.0.0"
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View File

@@ -0,0 +1,109 @@
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View File

@@ -1,4 +1,4 @@
openApiGeneratorVersion=3.3.2
openApiGeneratorVersion=4.0.0-SNAPSHOT
# BEGIN placeholders
# these are just placeholders to allow contributors to build directly

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<version>3.3.2</version>
<version>4.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -17,5 +17,5 @@ gradle generateGoWithInvalidSpec
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=3.3.2 openApiValidate
gradle -PopenApiGeneratorVersion=3.3.4 openApiValidate
```

View File

@@ -1 +1 @@
openApiGeneratorVersion=3.3.2
openApiGeneratorVersion=3.3.4

View File

@@ -11,7 +11,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.3.2</version>
<version>3.3.4</version>
<executions>
<execution>
<goals>

View File

@@ -12,7 +12,7 @@
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.3.2</version>
<version>3.3.4</version>
<executions>
<execution>
<goals>

View File

@@ -12,7 +12,7 @@
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.3.2</version>
<version>3.3.4</version>
<executions>
<execution>
<goals>

View File

@@ -12,7 +12,7 @@
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.3.2</version>
<version>3.3.4</version>
<executions>
<execution>
<goals>

View File

@@ -4,7 +4,7 @@
<parent>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<version>3.3.2</version>
<version>4.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<artifactId>openapi-generator-maven-plugin</artifactId>
@@ -15,6 +15,11 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.sonatype.plexus</groupId>
<artifactId>plexus-build-api</artifactId>
<version>0.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>

View File

@@ -42,6 +42,7 @@ import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.project.MavenProject;
import org.openapitools.codegen.CliOption;
@@ -50,9 +51,15 @@ import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.sonatype.plexus.build.incremental.BuildContext;
import org.sonatype.plexus.build.incremental.DefaultBuildContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
/**
* Goal which generates client/server code from a OpenAPI json/yaml definition.
*/
@@ -61,6 +68,13 @@ public class CodeGenMojo extends AbstractMojo {
private static final Logger LOGGER = LoggerFactory.getLogger(CodeGenMojo.class);
/**
* The build context is only avail when running from within eclipse.
* It is used to update the eclipse-m2e-layer when the plugin is executed inside the IDE.
*/
@Component
private BuildContext buildContext = new DefaultBuildContext();
@Parameter(name="validateSpec", required = false, defaultValue = "true")
private Boolean validateSpec;
@@ -307,6 +321,12 @@ public class CodeGenMojo extends AbstractMojo {
@Parameter(name = "skip", property = "codegen.skip", required = false, defaultValue = "false")
private Boolean skip;
/**
* Skip the execution if the source file is older than the output folder.
*/
@Parameter(name = "skipIfSpecIsUnchanged", property = "codegen.skipIfSpecIsUnchanged", required = false, defaultValue = "false")
private Boolean skipIfSpecIsUnchanged;
/**
* Add the output directory to the project as a source root, so that the generated java types
* are compiled and included in the project artifact.
@@ -329,274 +349,330 @@ public class CodeGenMojo extends AbstractMojo {
@Parameter(readonly = true, required = true, defaultValue = "${project}")
private MavenProject project;
public void setBuildContext(BuildContext buildContext) {
this.buildContext = buildContext;
}
@Override
public void execute() throws MojoExecutionException {
File inputSpecFile = new File(inputSpec);
addCompileSourceRootIfConfigured();
if (skip) {
getLog().info("Code generation is skipped.");
// Even when no new sources are generated, the existing ones should
// still be compiled if needed.
addCompileSourceRootIfConfigured();
return;
}
// attempt to read from config file
CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile);
// if a config file wasn't specified or we were unable to read it
if (configurator == null) {
configurator = new CodegenConfigurator();
}
configurator.setVerbose(verbose);
// now override with any specified parameters
if (validateSpec != null) {
configurator.setValidateSpec(validateSpec);
}
if (skipOverwrite != null) {
configurator.setSkipOverwrite(skipOverwrite);
}
if (removeOperationIdPrefix != null) {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
if (isNotEmpty(inputSpec)) {
configurator.setInputSpec(inputSpec);
}
if (isNotEmpty(gitUserId)) {
configurator.setGitUserId(gitUserId);
}
if (isNotEmpty(gitRepoId)) {
configurator.setGitRepoId(gitRepoId);
}
if (isNotEmpty(ignoreFileOverride)) {
configurator.setIgnoreFileOverride(ignoreFileOverride);
}
// TODO: After 3.0.0 release (maybe for 3.1.0): Fully deprecate lang.
if (isNotEmpty(generatorName)) {
configurator.setGeneratorName(generatorName);
// check if generatorName & language are set together, inform user this needs to be updated to prevent future issues.
if (isNotEmpty(language)) {
LOGGER.warn("The 'language' option is deprecated and was replaced by 'generatorName'. Both can not be set together");
throw new MojoExecutionException("Illegal configuration: 'language' and 'generatorName' can not be set both, remove 'language' from your configuration");
}
} else if (isNotEmpty(language)) {
LOGGER.warn("The 'language' option is deprecated and may reference language names only in the next major release (4.0). Please use 'generatorName' instead.");
configurator.setGeneratorName(language);
} else {
LOGGER.error("A generator name (generatorName) is required.");
throw new MojoExecutionException("The generator requires 'generatorName'. Refer to documentation for a list of options.");
}
configurator.setOutputDir(output.getAbsolutePath());
if (isNotEmpty(auth)) {
configurator.setAuth(auth);
}
if (isNotEmpty(apiPackage)) {
configurator.setApiPackage(apiPackage);
}
if (isNotEmpty(modelPackage)) {
configurator.setModelPackage(modelPackage);
}
if (isNotEmpty(invokerPackage)) {
configurator.setInvokerPackage(invokerPackage);
}
if (isNotEmpty(groupId)) {
configurator.setGroupId(groupId);
}
if (isNotEmpty(artifactId)) {
configurator.setArtifactId(artifactId);
}
if (isNotEmpty(artifactVersion)) {
configurator.setArtifactVersion(artifactVersion);
}
if (isNotEmpty(library)) {
configurator.setLibrary(library);
}
if (isNotEmpty(modelNamePrefix)) {
configurator.setModelNamePrefix(modelNamePrefix);
}
if (isNotEmpty(modelNameSuffix)) {
configurator.setModelNameSuffix(modelNameSuffix);
}
if (null != templateDirectory) {
configurator.setTemplateDir(templateDirectory.getAbsolutePath());
}
// Set generation options
if (null != generateApis && generateApis) {
System.setProperty(CodegenConstants.APIS, "");
} else {
System.clearProperty(CodegenConstants.APIS);
}
if (null != generateModels && generateModels) {
System.setProperty(CodegenConstants.MODELS, modelsToGenerate);
} else {
System.clearProperty(CodegenConstants.MODELS);
}
if (null != generateSupportingFiles && generateSupportingFiles) {
System.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesToGenerate);
} else {
System.clearProperty(CodegenConstants.SUPPORTING_FILES);
}
System.setProperty(CodegenConstants.MODEL_TESTS, generateModelTests.toString());
System.setProperty(CodegenConstants.MODEL_DOCS, generateModelDocumentation.toString());
System.setProperty(CodegenConstants.API_TESTS, generateApiTests.toString());
System.setProperty(CodegenConstants.API_DOCS, generateApiDocumentation.toString());
System.setProperty(CodegenConstants.WITH_XML, withXml.toString());
if (configOptions != null) {
// Retained for backwards-compataibility with configOptions -> instantiation-types
if (instantiationTypes == null && configOptions.containsKey("instantiation-types")) {
applyInstantiationTypesKvp(configOptions.get("instantiation-types").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> import-mappings
if (importMappings == null && configOptions.containsKey("import-mappings")) {
applyImportMappingsKvp(configOptions.get("import-mappings").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> type-mappings
if (typeMappings == null && configOptions.containsKey("type-mappings")) {
applyTypeMappingsKvp(configOptions.get("type-mappings").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> language-specific-primitives
if (languageSpecificPrimitives == null && configOptions.containsKey("language-specific-primitives")) {
applyLanguageSpecificPrimitivesCsv(configOptions
.get("language-specific-primitives").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> additional-properties
if (additionalProperties == null && configOptions.containsKey("additional-properties")) {
applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> reserved-words-mappings
if (reservedWordsMappings == null && configOptions.containsKey("reserved-words-mappings")) {
applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings")
.toString(), configurator);
}
}
//Apply Instantiation Types
if (instantiationTypes != null && (configOptions == null || !configOptions.containsKey("instantiation-types"))) {
applyInstantiationTypesKvpList(instantiationTypes, configurator);
}
//Apply Import Mappings
if (importMappings != null && (configOptions == null || !configOptions.containsKey("import-mappings"))) {
applyImportMappingsKvpList(importMappings, configurator);
}
//Apply Type Mappings
if (typeMappings != null && (configOptions == null || !configOptions.containsKey("type-mappings"))) {
applyTypeMappingsKvpList(typeMappings, configurator);
}
//Apply Language Specific Primitives
if (languageSpecificPrimitives != null && (configOptions == null || !configOptions.containsKey("language-specific-primitives"))) {
applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator);
}
//Apply Additional Properties
if (additionalProperties != null && (configOptions == null || !configOptions.containsKey("additional-properties"))) {
applyAdditionalPropertiesKvpList(additionalProperties, configurator);
}
//Apply Reserved Words Mappings
if (reservedWordsMappings != null && (configOptions == null || !configOptions.containsKey("reserved-words-mappings"))) {
applyReservedWordsMappingsKvpList(reservedWordsMappings, configurator);
}
if (environmentVariables != null) {
for (String key : environmentVariables.keySet()) {
originalEnvironmentVariables.put(key, System.getProperty(key));
String value = environmentVariables.get(key);
if (value == null) {
// don't put null values
value = "";
}
System.setProperty(key, value);
configurator.addSystemProperty(key, value);
}
}
final ClientOptInput input = configurator.toClientOptInput();
final CodegenConfig config = input.getConfig();
if (configOptions != null) {
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
input.getConfig().additionalProperties()
.put(langCliOption.getOpt(), configOptions.get(langCliOption.getOpt()));
}
}
}
if (configHelp) {
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t "
+ langCliOption.getOptionHelp().replaceAll("\n", "\n\t "));
System.out.println();
}
return;
}
adjustAdditionalProperties(config);
try {
if (skip) {
getLog().info("Code generation is skipped.");
return;
}
if (buildContext != null) {
if (buildContext.isIncremental()) {
if (inputSpec != null) {
if (inputSpecFile.exists()) {
if (!buildContext.hasDelta(inputSpecFile)) {
getLog().info(
"Code generation is skipped in delta-build because source-json was not modified.");
return;
}
}
}
}
}
if (skipIfSpecIsUnchanged) {
if (inputSpecFile.exists()) {
File storedInputSpecHashFile = getHashFile(inputSpecFile);
if(storedInputSpecHashFile.exists()) {
String inputSpecHash = Files.asByteSource(inputSpecFile).hash(Hashing.sha256()).toString();
String storedInputSpecHash = Files.asCharSource(storedInputSpecHashFile, Charsets.UTF_8).read();
if (inputSpecHash.equals(storedInputSpecHash)) {
getLog().info(
"Code generation is skipped because input was unchanged");
return;
}
}
}
}
// attempt to read from config file
CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile);
// if a config file wasn't specified or we were unable to read it
if (configurator == null) {
configurator = new CodegenConfigurator();
}
configurator.setVerbose(verbose);
// now override with any specified parameters
if (validateSpec != null) {
configurator.setValidateSpec(validateSpec);
}
if (skipOverwrite != null) {
configurator.setSkipOverwrite(skipOverwrite);
}
if (removeOperationIdPrefix != null) {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
if (isNotEmpty(inputSpec)) {
configurator.setInputSpec(inputSpec);
}
if (isNotEmpty(gitUserId)) {
configurator.setGitUserId(gitUserId);
}
if (isNotEmpty(gitRepoId)) {
configurator.setGitRepoId(gitRepoId);
}
if (isNotEmpty(ignoreFileOverride)) {
configurator.setIgnoreFileOverride(ignoreFileOverride);
}
// TODO: After 3.0.0 release (maybe for 3.1.0): Fully deprecate lang.
if (isNotEmpty(generatorName)) {
configurator.setGeneratorName(generatorName);
// check if generatorName & language are set together, inform user this needs to be updated to prevent future issues.
if (isNotEmpty(language)) {
LOGGER.warn("The 'language' option is deprecated and was replaced by 'generatorName'. Both can not be set together");
throw new MojoExecutionException(
"Illegal configuration: 'language' and 'generatorName' can not be set both, remove 'language' from your configuration");
}
} else if (isNotEmpty(language)) {
LOGGER.warn(
"The 'language' option is deprecated and may reference language names only in the next major release (4.0). Please use 'generatorName' instead.");
configurator.setGeneratorName(language);
} else {
LOGGER.error("A generator name (generatorName) is required.");
throw new MojoExecutionException("The generator requires 'generatorName'. Refer to documentation for a list of options.");
}
configurator.setOutputDir(output.getAbsolutePath());
if (isNotEmpty(auth)) {
configurator.setAuth(auth);
}
if (isNotEmpty(apiPackage)) {
configurator.setApiPackage(apiPackage);
}
if (isNotEmpty(modelPackage)) {
configurator.setModelPackage(modelPackage);
}
if (isNotEmpty(invokerPackage)) {
configurator.setInvokerPackage(invokerPackage);
}
if (isNotEmpty(groupId)) {
configurator.setGroupId(groupId);
}
if (isNotEmpty(artifactId)) {
configurator.setArtifactId(artifactId);
}
if (isNotEmpty(artifactVersion)) {
configurator.setArtifactVersion(artifactVersion);
}
if (isNotEmpty(library)) {
configurator.setLibrary(library);
}
if (isNotEmpty(modelNamePrefix)) {
configurator.setModelNamePrefix(modelNamePrefix);
}
if (isNotEmpty(modelNameSuffix)) {
configurator.setModelNameSuffix(modelNameSuffix);
}
if (null != templateDirectory) {
configurator.setTemplateDir(templateDirectory.getAbsolutePath());
}
// Set generation options
if (null != generateApis && generateApis) {
System.setProperty(CodegenConstants.APIS, "");
} else {
System.clearProperty(CodegenConstants.APIS);
}
if (null != generateModels && generateModels) {
System.setProperty(CodegenConstants.MODELS, modelsToGenerate);
} else {
System.clearProperty(CodegenConstants.MODELS);
}
if (null != generateSupportingFiles && generateSupportingFiles) {
System.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesToGenerate);
} else {
System.clearProperty(CodegenConstants.SUPPORTING_FILES);
}
System.setProperty(CodegenConstants.MODEL_TESTS, generateModelTests.toString());
System.setProperty(CodegenConstants.MODEL_DOCS, generateModelDocumentation.toString());
System.setProperty(CodegenConstants.API_TESTS, generateApiTests.toString());
System.setProperty(CodegenConstants.API_DOCS, generateApiDocumentation.toString());
System.setProperty(CodegenConstants.WITH_XML, withXml.toString());
if (configOptions != null) {
// Retained for backwards-compataibility with configOptions -> instantiation-types
if (instantiationTypes == null && configOptions.containsKey("instantiation-types")) {
applyInstantiationTypesKvp(configOptions.get("instantiation-types").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> import-mappings
if (importMappings == null && configOptions.containsKey("import-mappings")) {
applyImportMappingsKvp(configOptions.get("import-mappings").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> type-mappings
if (typeMappings == null && configOptions.containsKey("type-mappings")) {
applyTypeMappingsKvp(configOptions.get("type-mappings").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> language-specific-primitives
if (languageSpecificPrimitives == null && configOptions.containsKey("language-specific-primitives")) {
applyLanguageSpecificPrimitivesCsv(configOptions
.get("language-specific-primitives").toString(), configurator);
}
// Retained for backwards-compataibility with configOptions -> additional-properties
if (additionalProperties == null && configOptions.containsKey("additional-properties")) {
applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(),
configurator);
}
// Retained for backwards-compataibility with configOptions -> reserved-words-mappings
if (reservedWordsMappings == null && configOptions.containsKey("reserved-words-mappings")) {
applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings")
.toString(), configurator);
}
}
// Apply Instantiation Types
if (instantiationTypes != null && (configOptions == null || !configOptions.containsKey("instantiation-types"))) {
applyInstantiationTypesKvpList(instantiationTypes, configurator);
}
// Apply Import Mappings
if (importMappings != null && (configOptions == null || !configOptions.containsKey("import-mappings"))) {
applyImportMappingsKvpList(importMappings, configurator);
}
// Apply Type Mappings
if (typeMappings != null && (configOptions == null || !configOptions.containsKey("type-mappings"))) {
applyTypeMappingsKvpList(typeMappings, configurator);
}
// Apply Language Specific Primitives
if (languageSpecificPrimitives != null
&& (configOptions == null || !configOptions.containsKey("language-specific-primitives"))) {
applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator);
}
// Apply Additional Properties
if (additionalProperties != null && (configOptions == null || !configOptions.containsKey("additional-properties"))) {
applyAdditionalPropertiesKvpList(additionalProperties, configurator);
}
// Apply Reserved Words Mappings
if (reservedWordsMappings != null && (configOptions == null || !configOptions.containsKey("reserved-words-mappings"))) {
applyReservedWordsMappingsKvpList(reservedWordsMappings, configurator);
}
if (environmentVariables != null) {
for (String key : environmentVariables.keySet()) {
originalEnvironmentVariables.put(key, System.getProperty(key));
String value = environmentVariables.get(key);
if (value == null) {
// don't put null values
value = "";
}
System.setProperty(key, value);
configurator.addSystemProperty(key, value);
}
}
final ClientOptInput input = configurator.toClientOptInput();
final CodegenConfig config = input.getConfig();
if (configOptions != null) {
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
input.getConfig().additionalProperties()
.put(langCliOption.getOpt(), configOptions.get(langCliOption.getOpt()));
}
}
}
if (configHelp) {
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t "
+ langCliOption.getOptionHelp().replaceAll("\n", "\n\t "));
System.out.println();
}
return;
}
adjustAdditionalProperties(config);
new DefaultGenerator().opts(input).generate();
if (buildContext != null) {
buildContext.refresh(new File(getCompileSourceRoot()));
}
// Store a checksum of the input spec
File storedInputSpecHashFile = getHashFile(inputSpecFile);
String inputSpecHash = Files.asByteSource(inputSpecFile).hash(Hashing.sha256()).toString();
if (storedInputSpecHashFile.getParent() != null && !new File(storedInputSpecHashFile.getParent()).exists()) {
File parent = new File(storedInputSpecHashFile.getParent());
parent.mkdirs();
}
Files.asCharSink(storedInputSpecHashFile, Charsets.UTF_8).write(inputSpecHash);
} catch (Exception e) {
// Maven logs exceptions thrown by plugins only if invoked with -e
// I find it annoying to jump through hoops to get basic diagnostic information,
// so let's log it in any case:
if (buildContext != null) {
buildContext.addError(inputSpecFile, 0, 0, "unexpected error in Open-API generation", e);
}
getLog().error(e);
throw new MojoExecutionException(
"Code generation failed. See above for the full exception.");
}
}
addCompileSourceRootIfConfigured();
private File getHashFile(File inputSpecFile) {
return new File(output.getPath() + File.separator + ".openapi-generator" + File.separator + inputSpecFile.getName() + ".sha256");
}
private String getCompileSourceRoot() {
final Object sourceFolderObject =
configOptions == null ? null : configOptions
.get(CodegenConstants.SOURCE_FOLDER);
final String sourceFolder =
sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString();
String sourceJavaFolder = output.toString() + "/" + sourceFolder;
return sourceJavaFolder;
}
private void addCompileSourceRootIfConfigured() {
if (addCompileSourceRoot) {
final Object sourceFolderObject =
configOptions == null ? null : configOptions
.get(CodegenConstants.SOURCE_FOLDER);
final String sourceFolder =
sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString();
String sourceJavaFolder = output.toString() + "/" + sourceFolder;
project.addCompileSourceRoot(sourceJavaFolder);
project.addCompileSourceRoot(getCompileSourceRoot());
}
// Reset all environment variables to their original value. This prevents unexpected
@@ -611,10 +687,10 @@ public class CodeGenMojo extends AbstractMojo {
}
}
/**
* This method enables conversion of true/false strings in
* This method enables conversion of true/false strings in
* config.additionalProperties (configuration/configOptions) to proper booleans.
* This enables mustache files to handle the properties better.
*
*
* @param config
*/
private void adjustAdditionalProperties(final CodegenConfig config) {

View File

@@ -0,0 +1,17 @@
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<goals>
<goal>generate</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute>
<runOnIncremental>true</runOnIncremental>
<runOnConfiguration>true</runOnConfiguration>
</execute>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<version>3.3.2</version>
<version>4.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<artifactId>openapi-generator-online</artifactId>
@@ -13,7 +13,9 @@
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<spring-boot-version>2.0.7.RELEASE</spring-boot-version>
<springfox-version>2.8.0</springfox-version>
<junit-version>4.12</junit-version>
</properties>
<dependencyManagement>
<dependencies>
@@ -85,5 +87,23 @@
<artifactId>openapi-generator</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -19,11 +19,11 @@ package org.openapitools.codegen.online.service;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.online.api.GenApiDelegate;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.online.api.GenApiDelegate;
import org.openapitools.codegen.online.model.Generated;
import org.openapitools.codegen.online.model.GeneratorInput;
import org.openapitools.codegen.online.model.ResponseCode;
@@ -36,8 +36,9 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -68,12 +69,8 @@ public class GenApiService implements GenApiDelegate {
servers.sort(String.CASE_INSENSITIVE_ORDER);
}
private final NativeWebRequest request;
@Autowired
public GenApiService(NativeWebRequest request) {
this.request = request;
}
private NativeWebRequest request;
@Override
public Optional<NativeWebRequest> getRequest() {
@@ -114,33 +111,7 @@ public class GenApiService implements GenApiDelegate {
@Override
public ResponseEntity<ResponseCode> generateClient(String language, GeneratorInput generatorInput) {
String filename = Generator.generateClient(language, generatorInput);
String host = System.getenv("GENERATOR_HOST");
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
if (StringUtils.isBlank(host)) {
String scheme = servletRequest.getHeader("X-SSL");
String port = "";
if ("1".equals(scheme)) {
scheme = "https";
} else {
scheme = servletRequest.getScheme();
port = ":" + servletRequest.getServerPort();
}
host = scheme + "://" + servletRequest.getServerName() + port;
}
if (filename != null) {
String code = String.valueOf(UUID.randomUUID().toString());
Generated g = new Generated();
g.setFilename(filename);
g.setFriendlyName(language + "-client");
fileMap.put(code, g);
System.out.println(code + ", " + filename);
String link = host + "/api/gen/download/" + code;
return ResponseEntity.ok().body(new ResponseCode(code, link));
} else {
return ResponseEntity.status(500).build();
}
return getResponse(filename, language + "-client");
}
@Override
@@ -183,20 +154,27 @@ public class GenApiService implements GenApiDelegate {
String filename = Generator.generateServer(framework, generatorInput);
System.out.println("generated name: " + filename);
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
return getResponse(filename, framework + "-server");
}
String host =
servletRequest.getScheme() + "://" + servletRequest.getServerName() + ":"
+ servletRequest.getServerPort();
private ResponseEntity<ResponseCode> getResponse(String filename, String friendlyName) {
String host = System.getenv("GENERATOR_HOST");
UriComponentsBuilder uriBuilder;
if (!StringUtils.isBlank(host)) {
uriBuilder = UriComponentsBuilder.fromUriString(host);
} else {
uriBuilder = ServletUriComponentsBuilder.fromCurrentContextPath();
}
if (filename != null) {
String code = String.valueOf(UUID.randomUUID().toString());
String code = UUID.randomUUID().toString();
Generated g = new Generated();
g.setFilename(filename);
g.setFriendlyName(framework + "-server");
g.setFriendlyName(friendlyName);
fileMap.put(code, g);
System.out.println(code + ", " + filename);
String link = host + "/api/gen/download/" + code;
String link = uriBuilder.path("/api/gen/download/").path(code).toUriString();
return ResponseEntity.ok().body(new ResponseCode(code, link));
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

View File

@@ -50,7 +50,7 @@ public class Generator {
try {
config = CodegenConfigLoader.forName(language);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, String.format(Locale.ROOT,"Unsupported target %s supplied. %s",
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT,"Unsupported target %s supplied. %s",
language, e));
}
Map<String, CliOption> map = new LinkedHashMap<>();

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<version>3.3.2</version>
<version>4.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -27,6 +27,7 @@ import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.ServerVariable;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -261,4 +262,9 @@ public interface CodegenConfig {
public void setEnablePostProcessFile(boolean isEnablePostProcessFile);
// set OpenAPI and schemas
public void setGlobalOpenAPI(OpenAPI openAPI);
public void setGlobalSchemas(OpenAPI openAPI);
}

View File

@@ -221,6 +221,10 @@ public class CodegenConstants {
public static final String SOURCECODEONLY_GENERATION = "generateSourceCodeOnly";
public static final String SOURCECODEONLY_GENERATION_DESC = "Specifies that only a library source code is to be generated.";
public static final String PARCELIZE_MODELS = "parcelizeModels";
public static final String PARCELIZE_MODELS_DESC = "toggle \"@Parcelize\" for generated models";
// Not user-configurable. System provided for use in templates.
public static final String GENERATE_APIS = "generateApis";

View File

@@ -1,5 +1,7 @@
package org.openapitools.codegen;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.*;
public class CodegenDiscriminator {
@@ -85,4 +87,13 @@ public class CodegenDiscriminator {
public int hashCode() {
return Objects.hash(propertyName, mapping, mappedModels);
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("propertyName", propertyName)
.append("mapping", mapping)
.append("mappedModels", mappedModels)
.toString();
}
}

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