diff --git a/.activate.sh b/.activate.sh new file mode 100644 index 00000000..8d57f17b --- /dev/null +++ b/.activate.sh @@ -0,0 +1,4 @@ +#!/bin/bash +make install-hooks + +source venv/bin/activate diff --git a/.deactivate.sh b/.deactivate.sh new file mode 100644 index 00000000..3dfa40fb --- /dev/null +++ b/.deactivate.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +deactivate diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..9f835f03 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.iml +.* +local.properties +venv/ +build/ +out/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..abb6b143 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,27 @@ +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.0.0 + hooks: + - id: check-merge-conflict + - id: trailing-whitespace + exclude: .*\.mustache$ + - id: end-of-file-fixer + exclude: .*\.mustache$ + - id: pretty-format-json + args: [--autofix, --indent, '4'] + - id: check-yaml + - id: check-executables-have-shebangs +- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks + rev: v1.2.2 + hooks: + - id: pretty-format-java + args: [--autofix] + - id: pretty-format-kotlin + args: [--autofix] + - id: pretty-format-yaml + args: [--autofix, --indent, '2'] +- repo: https://github.com/Yelp/detect-secrets + rev: v0.11.3 + hooks: + - id: detect-secrets + args: [--baseline, .secrets.baseline] diff --git a/.secrets.baseline b/.secrets.baseline new file mode 100644 index 00000000..181ba7e3 --- /dev/null +++ b/.secrets.baseline @@ -0,0 +1,36 @@ +{ + "exclude_regex": null, + "generated_at": "2019-01-28T12:41:36Z", + "plugins_used": [ + { + "name": "AWSKeyDetector" + }, + { + "base64_limit": 4.5, + "name": "Base64HighEntropyString" + }, + { + "name": "BasicAuthDetector" + }, + { + "hex_limit": 3, + "name": "HexHighEntropyString" + }, + { + "name": "KeywordDetector" + }, + { + "name": "PrivateKeyDetector" + } + ], + "results": { + "gradle.properties.example": [ + { + "hashed_secret": "6f9583b0d701174f6b64698f940f9e1470612638", + "line_number": 2, + "type": "Secret Keyword" + } + ] + }, + "version": "0.11.3" +} diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..6bcc8383 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,31 @@ +language: android + +jdk: +- oraclejdk8 + +os: +- linux + +android: + components: + - tools + - platform-tools + - build-tools-28.0.3 + - android-28 + +before_cache: +- rm -f ${HOME}/.gradle/caches/modules-2/modules-2.lock +- rm -fr ${HOME}/.gradle/caches/*/plugin-resolution/ + +cache: + directories: + - ${HOME}/.gradle/caches/ + - ${HOME}/.gradle/wrapper/ + - ${HOME}/.m2 + +script: +- ./gradlew plugin:build +- ./gradlew plugin:publishToMavenLocal +- ./gradlew generateSwagger +- ./gradlew assembleDebug +- ./gradlew check diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..b78931b5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2015-2016 Yelp Inc. + +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. diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..09828feb --- /dev/null +++ b/Makefile @@ -0,0 +1,8 @@ +.PHONY: install-hooks + +venv: + virtualenv venv + ./venv/bin/pip install pre-commit + +install-hooks: venv + ./venv/bin/pre-commit install --install-hooks diff --git a/README.md b/README.md new file mode 100644 index 00000000..9d5f8148 --- /dev/null +++ b/README.md @@ -0,0 +1,156 @@ +# Swagger Gradle Codegen + +[![Plugin Portal](https://img.shields.io/maven-metadata/v/https/plugins.gradle.org/m2/com/yelp/codegen/plugin/com.yelp.codegen.plugin.gradle.plugin/maven-metadata.xml.svg?label=Gradle%20Plugin%20Portal&colorB=brightgreen)](https://plugins.gradle.org/plugin/com.yelp.codegen.plugin) [![License](https://img.shields.io/badge/license-Apache2.0%20License-orange.svg)](https://opensource.org/licenses/Apache2.0) [![Twitter](https://img.shields.io/badge/Twitter-@YelpEngineering-blue.svg)](https://twitter.com/YelpEngineering) + +A Gradle plugin to **generate networking code** from a **Swagger spec file**. + +This plugin wraps [swagger-codegen](https://github.com/swagger-api/swagger-codegen), and exposes a configurable `generateSwagger` gradle task that you can plug inside your gradle build/workflows. + +## Getting Started + +**Swagger Gradle Codegen** is distributed through [Gradle Plugin Portal](https://plugins.gradle.org/). To use it you need to add the following dependency to your gradle files. Please note that those code needs to be added the gradle file of the module where you want to generate the code (**not the top level** build.gradle\[.kts\] file). + +If you're using the Groovy Gradle files: +```groovy +buildscript { + repositories { + maven { url "https://plugins.gradle.org/m2/" } + } + + dependencies { + classpath "com.yelp.codegen:plugin:" + } +} + +apply plugin: "com.yelp.codegen.plugin" + +generateSwagger { + platform = "kotlin" + packageName = "com.yelp.codegen.samples" + inputFile = file("./sample_specs.json") + outputDir = file("./src/main/java/") +} +``` + +If you're using the Kotlin Gradle files: + +```kotlin +plugins { + id("com.yelp.codegen.plugin") version "" +} + +generateSwagger { + platform = "kotlin" + packageName = "com.yelp.codegen.samples" + inputFile = file("./sample_specs.json") + outputDir = file("./src/main/java/") +} +``` + +Please note that the `generateSwagger { }` block is **needed** in order to let the plugin work. + +Once you setup the plugin correctly, you can call the `:generateSwagger` gradle task, that will run the code generation with the configuration you provided. + +## Supported platforms + +The Swagger Gradle Codegen is designed to support multiple platforms. For every platform, we provide **templates** that are tested and generates opinionated code. + +Here the list of the supported platforms: + +| Platform | Description | +| -------- | ------------------------------------------ | +| `kotlin` | Generates Kotlin code, with RxJava2 for async calls, Moshi for serialization and ThreeTenABP for Data management | + +We're looking forward to more platforms to support in the future. Contributions are more than welcome. + +## Configuration + +To configure the generator, please use the `generateSwagger { }` block. Here an example of this block with all the properties. + +```kotlin +generateSwagger { + platform = "kotlin" + packageName = "com.yelp.codegen.integrations" + specName = "integration" + specVersion = "1.0.0" + inputFile = file("../sample_specs.json") + outputDir = file("./src/main/java/") + features { + headersToRemove = ["Accept-Language"] + } +} +``` + +And here a table with all the properties and their default values: + +| Property | Description | Default | +| -------- | ----------- | ------- | +| `inputFile` | Defines the path to the Swagger spec file | **REQUIRED** | +| `platform` | Defines the platform/templates that will be used. See [Supported platforms](#Supported-platforms-) for a list of them. | `"kotlin"` | +| `packageName` | Defines the fully qualified package name that will be used as root when generating the code. | `"com.codegen.default"` | +| `specName` | Defines the name of the service that is going to be built. | `"defaultname"` | +| `specVersion` | Defines the version of the spec that is going to be used. | If not provided, the version will be read from the specfile. If version is missing will default to `"0.0.0"` | +| `outputDir` | Defines the output root folder for the generated files. | `$buildDir/gen` | +| `extraFiles` | Defines a folder with extra files that will be copied over after the generation (e.g. util classes or overrides). | not set by default | + +Please note that all those properties can be configured with **command line flags** that mirrors 1:1 the property name. E.g.: + +```bash +./gradlew generateSwagger --inputFile=./sample/specs.json +``` + +### Extra Features + +You can use the `features { }` block to specify customization or enabled/disable specific features for your generator. + +Here a list of all the supported features: + +| Feature | Description | Command line | +| -------- | ----------- | ------------ | +| `headersToRemove` | List of headers that needs to be ignored for every endpoints. The headers in this list will be dropped and not generated as parameters for the endpoints. | `--featureHeaderToRemove=` | + +## Examples + +You can find some **examples** in this repository to help you set up your generator environment. + +* [sample-groovy-android](/sample-groovy-android) Contains an example of an Android Library configured with a `build.gradle` file, using Groovy as scripting language. + +* [sample-kotlin-android](/sample-kotlin-android) Contains an example of an Android Library configured with a `build.gradle.kts` file, using Kotlin as scripting language. + +## Building + +To contribute or to start developing the Swagger Codegen Plugin, you need to set up your environment. + +Make sure you have: +- Python (needed for pre-commit hook) +- Java/Kotlin (needed for compiling the plugin code) + +We also recommend you set up: +- [aactivator](https://github.com/Yelp/aactivator) To correctly manage your venv connected to this project +- [IntelliJ IDEA](https://www.jetbrains.com/idea/download/) Either the Community or the Ultimate edition are great to contribute to the plugin. + +Before starting developing, please run: + +``` +make install-hooks +``` + +This will take care of installing the pre-commit hooks to keep a consistent style in the codebase. + +While developing, you can run tests on the plugin using: + +``` +./gradlew plugin:test +``` + +Make sure your tests are all green ✅ locally before submitting PRs. + +## Contributing + +We're looking for contributors! Feel free to open issues/pull requests to help me improve this project. + +If you found a new issue related to incompatible Swagger specs, please attach also the **spec file** to help investigate the issue. + +## License 📄 + +This project is licensed under the Apache 2.0 License - see the [License](License) file for details diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..38ab26e1 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,10 @@ +group = PublishingVersions.PLUGIN_GROUP +version = PublishingVersions.PLUGIN_VERSION + +subprojects { + repositories { + google() + mavenCentral() + jcenter() + } +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 00000000..aebe2615 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { + `kotlin-dsl` +} +repositories { + mavenCentral() +} diff --git a/buildSrc/src/main/java/com/yelp/codegen/gradle/PublishingVersions.kt b/buildSrc/src/main/java/com/yelp/codegen/gradle/PublishingVersions.kt new file mode 100644 index 00000000..4d1f7170 --- /dev/null +++ b/buildSrc/src/main/java/com/yelp/codegen/gradle/PublishingVersions.kt @@ -0,0 +1,7 @@ +@file:Suppress("Unused") + +object PublishingVersions { + const val PLUGIN_VERSION = "1.0.0" + const val PLUGIN_GROUP = "com.yelp.codegen" + const val PLUGIN_ARTIFACT = "plugin" +} diff --git a/gradle.properties.example b/gradle.properties.example new file mode 100644 index 00000000..f672b821 --- /dev/null +++ b/gradle.properties.example @@ -0,0 +1,2 @@ +gradle.publish.key= +gradle.publish.secret= diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..457aad0d Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ee671127 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.0-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..af6708ff --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..0f8d5937 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts new file mode 100644 index 00000000..57aa4d13 --- /dev/null +++ b/plugin/build.gradle.kts @@ -0,0 +1,42 @@ +import org.gradle.jvm.tasks.Jar + +group = rootProject.group +version = rootProject.version + +plugins { + java + `kotlin-dsl` + `maven-publish` + kotlin("jvm") version "1.3.20" + id("com.gradle.plugin-publish") version "0.10.0" +} + +dependencies { + implementation(kotlin("stdlib-jdk8")) + + implementation(gradleApi()) + + implementation("commons-cli:commons-cli:1.4") + implementation("com.google.guava:guava:27.0-jre") + implementation("io.swagger:swagger-codegen:2.3.1") + implementation("org.json:json:20180813") +} + +tasks.register("sourcesJar") { + from(sourceSets.main.get().allJava) + classifier = "sources" +} + +// Configuration Block for the Plugin Marker artifact on Plugin Central +pluginBundle { + website = "https://github.com/Yelp/swagger-gradle-codegen" + vcsUrl = "https://github.com/Yelp/swagger-gradle-codegen" + description = "A Gradle plugin to generate networking code from Swagger Specs" + tags = listOf("swagger", "codegen", "retrofit", "android", "kotlin", "networking") + + plugins { + getByName("com.yelp.codegen.plugin") { + displayName = "Swagger Gradle Codegen" + } + } +} diff --git a/plugin/src/main/java/com/yelp/codegen/KotlinGenerator.kt b/plugin/src/main/java/com/yelp/codegen/KotlinGenerator.kt new file mode 100644 index 00000000..4bd99328 --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/KotlinGenerator.kt @@ -0,0 +1,428 @@ +@file:Suppress("NOTHING_TO_INLINE") + +package com.yelp.codegen + +import com.yelp.codegen.utils.KotlinLangUtils +import com.yelp.codegen.utils.safeSuffix +import com.yelp.codegen.utils.sanitizeKotlinSpecificNames +import com.yelp.codegen.utils.toCamelCase +import com.yelp.codegen.utils.toPascalCase +import io.swagger.codegen.CodegenConstants +import io.swagger.codegen.CodegenModel +import io.swagger.codegen.CodegenOperation +import io.swagger.codegen.CodegenParameter +import io.swagger.codegen.CodegenProperty +import io.swagger.codegen.DefaultCodegen +import io.swagger.codegen.SupportingFile +import io.swagger.models.Model +import io.swagger.models.Operation +import io.swagger.models.Swagger +import io.swagger.models.properties.Property +import java.io.File + +class KotlinGenerator : SharedCodegen() { + + companion object { + /** + * This number represents the version of the kotlin template + * Please note that is independent from the Plugin version + */ + @JvmStatic val VERSION = 11 + } + + private val apiDocPath = "docs/" + private val modelDocPath = "docs/" + + private val retrofitImport = mapOf( + "GET" to "retrofit2.http.GET", + "DELETE" to "retrofit2.http.DELETE", + "PATCH" to "retrofit2.http.PATCH", + "POST" to "retrofit2.http.POST", + "PUT" to "retrofit2.http.PUT" + ) + + /** + * Constructs an instance of `KotlinAndroidGenerator`. + */ + init { + languageSpecificPrimitives = KotlinLangUtils.kotlinLanguageSpecificPrimitives + reservedWords = KotlinLangUtils.kotlinReservedWords + defaultIncludes = KotlinLangUtils.kotlinDefaultIncludes + typeMapping = KotlinLangUtils.kotlinTypeMapping + instantiationTypes = KotlinLangUtils.kotlinInstantiationTypes + importMapping = KotlinLangUtils.kotlinImportMapping + + templateDir = "kotlin" + outputFolder = "generated-code${File.separator}android-kotlin-client" + modelTemplateFiles["model.mustache"] = ".kt" + apiTemplateFiles["retrofit2/api.mustache"] = ".kt" + } + + /* + * ABSTRACT FIELDS AND CONFIG FUNCTIONS + ==================================================== */ + + override val platform = "android" + + override fun getName() = "kotlin" + + override fun getHelp() = "Generates code for a Kotlin Android client." + + override fun modelPackage() = "$packageName.models" + + override fun apiPackage() = "$packageName.apis" + + private val groupId: String + get() = additionalProperties[GROUP_ID] as String? ?: "" + + private val artifactId: String + get() = additionalProperties[ARTIFACT_ID] as String? ?: "" + + private val packageName: String + get() = "$groupId.$artifactId" + + private val toolsPackage: String + get() = "$packageName.tools" + + /* + * FOLDERS SETUP + ==================================================== */ + + override fun apiDocFileFolder() = "$outputFolder${File.separator}$apiDocPath" + + override fun apiFileFolder() = + "$outputFolder${File.separator}" + apiPackage() + .replace('.', File.separatorChar) + + /* + * SHARED CODEGEN SETUP + ==================================================== */ + + override val mustacheTags + get() = hashMapOf( + CodegenConstants.GROUP_ID to groupId, + CodegenConstants.ARTIFACT_ID to artifactId, + CodegenConstants.PACKAGE_NAME to packageName, + CodegenConstants.API_PACKAGE to apiPackage(), + CodegenConstants.MODEL_PACKAGE to modelPackage(), + "apiDocPath" to apiDocPath, + "modelDocPath" to modelDocPath, + "service" to serviceName, + "newline" to "\n" + ) + + override val supportFiles: Collection + get() { + val toolsFolder = toolsPackage.replace(".", File.separator).plus(File.separator) + val toolsFiles = listOf( + "CollectionFormatConverterFactory.kt", + "CollectionFormats.kt", + "EnumToValueConverterFactory.kt", + "GeneratedCodeConverters.kt", + "TypesAdapters.kt", + "WrapperConverterFactory.kt", + "XNullable.kt", + "XNullableAdapterFactory.kt" + ) + supportingFiles.addAll(toolsFiles.map { SupportingFile("tools/$it.mustache", toolsFolder, it) }) + return supportingFiles + } + + /** No testing files are needed on Kotlin Generator */ + override val testingSupportFiles = listOf() + + override fun listTypeWrapper(listType: String, innerType: String) = + "$listType<$innerType>" + + override fun mapTypeWrapper(mapType: String, innerType: String) = + "$mapType<${typeMapping["string"]}, $innerType>" + + override fun nullableTypeWrapper(baseType: String) = + baseType.safeSuffix("?") + + /* + * ESCAPING + ==================================================== */ + + override fun initalizeSpecialCharacterMapping() { + super.initalizeSpecialCharacterMapping() + // Kotlin specific. + specialCharReplacements[";"] = "Semicolon" + specialCharReplacements.remove("_") + } + + override fun isReservedWord(word: String?) = word in reservedWords + + // remove " to avoid code injection + override fun escapeQuotationMark(input: String) = input.replace("\"", "") + + override fun escapeReservedWord(name: String) = + if (name in reservedWords) { + "`$name`" + } else { + name + } + + override fun escapeUnsafeCharacters(input: String) = + input.replace("*/", "*_/").replace("/*", "/_*") + + /* + * CODEGEN FUNCTIONS + ==================================================== */ + + override fun fromModel(name: String, model: Model, allDefinitions: MutableMap?): CodegenModel { + val codegenModel = super.fromModel(name, model, allDefinitions) + addRequiredImports(codegenModel) + return codegenModel + } + + private fun addRequiredImports(codegenModel: CodegenModel) { + // If there are any vars, we will mark them with the @Json annotation so we have to make sure to import it + if (codegenModel.vars.isNotEmpty() || codegenModel.isEnum) { + codegenModel.imports.add("com.squareup.moshi.Json") + } + + // Add import for @XNullable annotation if there are any XNullable properties + for (property in codegenModel.allVars) { + if (X_NULLABLE in property.vendorExtensions) { + codegenModel.imports.add("$toolsPackage.XNullable") + break + } + } + } + + override fun postProcessModelProperty(model: CodegenModel, property: CodegenProperty) { + super.postProcessModelProperty(model, property) + + if (property.isEnum) { + property.datatypeWithEnum = postProcessDataTypeWithEnum(model.classname, property) + } + } + + /** + * When handling inner enums, we want to prefix their class name, when using them, with their containing class, + * to avoid name conflicts. + */ + private fun postProcessDataTypeWithEnum(modelClassName: String, codegenProperty: CodegenProperty): String { + val name = "$modelClassName.${codegenProperty.enumName}" + + val baseType = if (codegenProperty.isContainer) { + val type = checkNotNull(typeMapping[codegenProperty.containerType]) + "$type<$name>" + } else { + name + } + + return if (codegenProperty.isNullable()) { + nullableTypeWrapper(baseType) + } else { + baseType + } + } + + /** + * Returns the swagger type for the property + * + * @param property Swagger property object + * @return string presentation of the type + */ + override fun getSwaggerType(property: Property): String? { + val swaggerType = super.getSwaggerType(property) + val type: String + // This maps, for example, long -> kotlin.Long based on hashes in this type's constructor + if (swaggerType in typeMapping) { + type = checkNotNull(typeMapping[swaggerType]) + if (type in languageSpecificPrimitives) { + return toModelName(type) + } + } else { + type = swaggerType + } + return toModelName(type) + } + + /** + * Output the type declaration of the property. + * + * @param property Swagger Property object + * @return a string presentation of the property type + */ + override fun getTypeDeclaration(property: Property): String { + val resolvedType = resolvePropertyType(property) + + return if (property.isNullable()) { + nullableTypeWrapper(resolvedType) + } else { + resolvedType + } + } + + override fun modelDocFileFolder(): String { + return "$outputFolder${File.separator}$modelDocPath" + } + + override fun modelFileFolder(): String { + return outputFolder + File.separator + modelPackage().replace('.', File.separatorChar) + } + + /** + * Return the sanitized variable name for enum + * + * @param value enum variable name + * @param datatype data type + * @return the sanitized variable name for enum + */ + override fun toEnumVarName(value: String, datatype: String): String { + (if (value.isEmpty()) "EMPTY" else value) + .sanitizeKotlinSpecificNames(specialCharReplacements) + .toUpperCase() + .let { + return escapeReservedWord(it) + } + } + + override fun toVarName(name: String): String { + return escapeReservedWord(name.toCamelCase()) + } + + /** + * Return the fully-qualified "Model" name for import + * + * @param name the name of the "Model" + * @return the fully-qualified "Model" name for import + */ + override fun toModelImport(name: String): String { + // toModelImport is called while processing operations, but DefaultCodegen doesn't + // define imports correctly with fully qualified primitives and models as defined in this generator. + return when { + name.isFullyQualifiedImportName() -> name + needToImport(name) -> super.toModelImport(name) + else -> name + } + } + + override fun addImport(model: CodegenModel, type: String?) { + if (type != null && needToImport(type) && type in importMapping) { + model.imports.add(type) + } + } + + /** + * Output the proper model name (capitalized). + * In case the name belongs to the TypeSystem it won't be renamed. + * + * @param name the name of the model + * @return capitalized model name + */ + override fun toModelName(name: String): String { + return if (name in importMapping) { + name + } else { + matchXModel(name) + .split(".").last() + .toPascalCase() + .sanitizeKotlinSpecificNames(specialCharReplacements) + .apply { escapeReservedWord(this) } + } + } + + /** + * Output the proper enum name (capitalized). We append a 'Enum' at the end of the name to avoid + * name clashes when enums are inner classes. + * + * Please note that this method is providing the same behavior as [DefaultCodegen.toEnumName] + * and might eventually be refactored. + * + * @param property the name of the model + * @return capitalized enum name (with appended 'Enum'). + */ + override fun toEnumName(property: CodegenProperty): String { + return toModelName(property.name) + "Enum" + } + + override fun toModelFilename(name: String): String = toModelName(name) + + /** + * Check if a name is of the type `com.x.name`, which means it has a fully qualified package. + */ + private inline fun String.isFullyQualifiedImportName() = "." in this + + override fun postProcessModels(objs: Map): Map { + val processedModels = postProcessModelsEnum(super.postProcessModels(objs)) + + // Sort imports. Not strictly needed, neater. + @Suppress("UNCHECKED_CAST") + val imports = processedModels["imports"] as MutableList> + imports.sortBy { it["import"] } + + return processedModels + } + + override fun fromOperation( + path: String?, + httpMethod: String?, + operation: Operation?, + definitions: MutableMap?, + swagger: Swagger? + ): CodegenOperation { + val codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, swagger) + + retrofitImport.get(codegenOperation.httpMethod)?.let { codegenOperation.imports.add(it) } + codegenOperation.allParams.forEach { codegenParameter: CodegenParameter -> + codegenParameter.collectionFormat?.let { + val importName = "$toolsPackage.${it.toUpperCase()}" + if (importName !in codegenOperation.imports) { + codegenOperation.imports.add(importName) + } + } + } + + when { + codegenOperation.isResponseFile -> { + codegenOperation.returnType = "Single" + codegenOperation.imports.add("okhttp3.ResponseBody") + codegenOperation.imports.add("io.reactivex.Single") + } + codegenOperation.returnType == null -> { + codegenOperation.returnType = "Completable" + codegenOperation.imports.add("io.reactivex.Completable") + } + else -> { + codegenOperation.returnType = "Single<${codegenOperation.returnType}>" + codegenOperation.imports.add("io.reactivex.Single") + } + } + + codegenOperation.imports.add("retrofit2.http.Headers") + codegenOperation.vendorExtensions[X_OPERATION_ID] = operation?.operationId + + getHeadersToIgnore().forEach { headerName -> + ignoreHeaderParameter(headerName, codegenOperation) + } + return codegenOperation + } + + override fun postProcessOperations(objs: Map): Map { + // Cleanup imports, by removing the default includes, and sorting them by alphabetical order. + @Suppress("UNCHECKED_CAST") + val allImports = objs["imports"] as MutableList>? + allImports?.also { imports -> + val iterator = imports.iterator() + while (iterator.hasNext()) { + val import = iterator.next()["import"] + if (import in defaultIncludes) { + iterator.remove() + } + } + imports.sortBy { it["import"] } + } + return objs + } + + override fun preprocessSwagger(swagger: Swagger) { + super.preprocessSwagger(swagger) + + // Override the swagger version with the one provided from command line. + swagger.info.version = additionalProperties[SPEC_VERSION] as String + } +} diff --git a/plugin/src/main/java/com/yelp/codegen/Main.kt b/plugin/src/main/java/com/yelp/codegen/Main.kt new file mode 100644 index 00000000..e5f75008 --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/Main.kt @@ -0,0 +1,93 @@ +@file:JvmName("Main") + +package com.yelp.codegen + +import com.fasterxml.jackson.core.PrettyPrinter +import io.swagger.codegen.DefaultGenerator +import io.swagger.codegen.config.CodegenConfigurator +import io.swagger.parser.SwaggerParser +import io.swagger.util.Json +import org.apache.commons.cli.CommandLine +import org.apache.commons.cli.CommandLineParser +import org.apache.commons.cli.DefaultParser +import org.apache.commons.cli.Option +import org.apache.commons.cli.Options +import java.io.File + +fun main(args: Array) { + val options = Options() + options.addRequiredOption( + "p", + "platform", + true, + "The platform to generate") + options.addRequiredOption( + "i", + "input", + true, + "Path to the input spec") + options.addRequiredOption( + "o", + "output", + true, + "Path to the output directory") + options.addRequiredOption( + "s", + "service", + true, + "Name of the service to build") + options.addRequiredOption( + "v", + "version", + true, + "Version to use when generating the code.") + options.addRequiredOption( + "g", + "groupid", + true, + "The fully qualified domain name of company/organization.") + options.addRequiredOption( + "a", + "artifactid", + true, + "The artifact id to be used when generating the code.") + options.addOption( + Option.builder("ignoreheaders") + .hasArg().argName("Comma separated list of headers to ingore") + .desc("A comma separated list of headers that will be ignored by the generator") + .build() + ) + + val parser: CommandLineParser = DefaultParser() + val parsed: CommandLine = parser.parse(options, args) + + val specVersion = parsed['v'] + + val configurator = CodegenConfigurator() + configurator.lang = parsed['p'] + configurator.inputSpec = parsed['i'] + configurator.outputDir = parsed['o'] + + configurator.addAdditionalProperty(LANGUAGE, parsed['p']) + configurator.addAdditionalProperty(SPEC_VERSION, specVersion) + configurator.addAdditionalProperty(SERVICE_NAME, parsed['s']) + configurator.addAdditionalProperty(GROUP_ID, parsed['g']) + configurator.addAdditionalProperty(ARTIFACT_ID, parsed['a']) + configurator.addAdditionalProperty(HEADERS_TO_IGNORE, parsed["ignoreheaders"]) + + DefaultGenerator().opts(configurator.toClientOptInput()).generate() + copySpec(checkNotNull(configurator.inputSpec), checkNotNull(configurator.outputDir)) +} + +fun copySpec(inputSpec: String, outputDirectory: String) { + val swagger = SwaggerParser().read(inputSpec) + Json.mapper().writer(null as PrettyPrinter?).writeValue(File("$outputDirectory/swagger.json"), swagger) +} + +private operator fun CommandLine.get(opt: Char): String? { + return getOptionValue(opt, null) +} + +private operator fun CommandLine.get(opt: String): String? { + return getOptionValue(opt, null) +} diff --git a/plugin/src/main/java/com/yelp/codegen/SharedCodegen.kt b/plugin/src/main/java/com/yelp/codegen/SharedCodegen.kt new file mode 100644 index 00000000..6864ce0d --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/SharedCodegen.kt @@ -0,0 +1,408 @@ +package com.yelp.codegen + +import com.yelp.codegen.utils.InlineModelResolver +import com.yelp.codegen.utils.safeSuffix +import io.swagger.codegen.CodegenConfig +import io.swagger.codegen.CodegenModel +import io.swagger.codegen.CodegenOperation +import io.swagger.codegen.CodegenProperty +import io.swagger.codegen.CodegenType +import io.swagger.codegen.DefaultCodegen +import io.swagger.codegen.SupportingFile +import io.swagger.models.ArrayModel +import io.swagger.models.Model +import io.swagger.models.ModelImpl +import io.swagger.models.Swagger +import io.swagger.models.properties.ArrayProperty +import io.swagger.models.properties.MapProperty +import io.swagger.models.properties.Property +import io.swagger.models.properties.RefProperty +import io.swagger.models.properties.StringProperty +import java.io.File + +const val SPEC_VERSION = "spec_version" +const val LANGUAGE = "language" +const val SERVICE_NAME = "service_name" +const val ARTIFACT_ID = "artifact_id" +const val GROUP_ID = "group_id" +const val HEADERS_TO_IGNORE = "headers_to_ignore" + +internal const val X_NULLABLE = "x-nullable" +internal const val X_MODEL = "x-model" +internal const val X_OPERATION_ID = "x-operation-id" + +abstract class SharedCodegen : DefaultCodegen(), CodegenConfig { + + // Reference to the Swagger Specs + protected var swagger: Swagger? = null + private val xModelMatches = mutableMapOf() + + override fun getTag() = CodegenType.CLIENT + + /** + * Return the platform for which the concrete codegen instance is generating code for + */ + protected abstract val platform: String + + /** + * Add all the mustache tags needed for the rendering that are dependent + * on the specific language + */ + protected abstract val mustacheTags: Map + + /** + * Add generator support files. NOTE: testing files should not be in here + */ + protected abstract val supportFiles: Collection + + /** + * Add generator support files for testing the final generated code. + */ + protected abstract val testingSupportFiles: Collection + + /** + * Returns the provided service name from the command line invocation + */ + protected val serviceName: String get() = this.additionalProperties[SERVICE_NAME] as String + + /** + * Returns the /main/resources directory to access the .mustache files + */ + protected val resourcesDirectory: File + get() = File(this.javaClass.classLoader.getResource(templateDir).path.safeSuffix(File.separator)) + + override fun processOpts() { + super.processOpts() + this.additionalProperties.putAll(mustacheTags) + this.supportingFiles.addAll(supportFiles) + this.supportingFiles.addAll(testingSupportFiles) + } + + override fun preprocessSwagger(swagger: Swagger) { + super.preprocessSwagger(swagger) + + mapXModel(swagger) + this.swagger = swagger + } + + override fun addAdditionPropertiesToCodeGenModel(codegenModel: CodegenModel?, swaggerModel: ModelImpl?) { + val additionalProperties = swaggerModel?.additionalProperties + if (additionalProperties != null) { + codegenModel?.additionalPropertiesType = this.getSwaggerType(additionalProperties) + + // If the model has additional properties at the top level, we want to create a typealias. + // Please note that definitions with properties and additionalProperties at the top level will be + // generated as typealias as well (`properties` will be lost). + codegenModel?.isAlias = true + } + } + + /** + * Creates a map of all x-model declarations (or title as a fallback), so that they can be used later when + * computing models names. + */ + private fun mapXModel(swagger: Swagger) { + InlineModelResolver().flatten(swagger) + swagger.definitions.forEach { name, model -> + (model.vendorExtensions?.get(X_MODEL) as? String?)?.let { x_model -> + xModelMatches[name] = x_model + } + xModelMatches[name] ?: model.title?.let { title -> + xModelMatches[name] = title + } + } + } + + /** + * Returns the x-model alternative name if it was defined + */ + fun matchXModel(name: String): String { + return xModelMatches[name] ?: name + } + + /** + * Method to propagate all the X-Nullable annotations from the referenced definition to the place where that + * reference is used. + * + * We need to investigate all the [RefProperty] of the current [Model] parameter, and check if their definition + * in the `allDefinitions` object is marked as x-nullable. + * + * This method is covering those cases: + * - Property that are using refs + * - AdditionalProperties at the top level that are using refs + * - Arrays at the top level that are using refs + * + * This is making sure that types are annotated properly when they're used. E.g. when used in Retrofit Apis. + */ + protected fun propagateXNullable(model: Model, allDefinitions: MutableMap?) { + if (allDefinitions == null) { + return + } + // If the model has properties, we need to investigate all of them. + if (model.properties != null) { + propagateXNullableToProperties(model, allDefinitions) + } + // If the model has additionalProperties at the top level, investigate it. + if (model is ModelImpl && model.additionalProperties != null && model.additionalProperties is RefProperty) { + propagateXNullableVendorExtension(model.additionalProperties as RefProperty, allDefinitions) + } + // If the model has `items` (is an array) at the top level, investigate it. + if (model is ArrayModel && model.items != null && model.items is RefProperty) { + propagateXNullableVendorExtension(model.items as RefProperty, allDefinitions) + } + } + + override fun fromModel(name: String, model: Model, allDefinitions: MutableMap?): CodegenModel { + propagateXNullable(model, allDefinitions) + val codegenModel = super.fromModel(name, model, allDefinitions) + + // Top level array Models should generate a typealias. + if (codegenModel.isArrayModel) { + codegenModel.isAlias = true + } + // If model is an Alias will generate a typealias. We need to check if the type is aliasing + // to any 'x-nullable' annotated model. + if (codegenModel.isAlias) { + codegenModel.dataType = getAliasTypeDeclaration(codegenModel) + checkForEnumsInTopLevel(codegenModel, model) + } + + handleXNullable(codegenModel) + return codegenModel + } + + /** + * Find variables in the model that contain the x-nullable vendorExtensions, + * and mark them as optional instead of required. + */ + internal open fun handleXNullable(codegenModel: CodegenModel) { + val requiredIterator = codegenModel.requiredVars.iterator() + while (requiredIterator.hasNext()) { + val property = requiredIterator.next() + if (property.vendorExtensions[X_NULLABLE] == true) { + requiredIterator.remove() + property.required = false + codegenModel.optionalVars.add(property) + codegenModel.hasOptional = true + } + } + // If we moved all required vars to optional because they are all x-nullable, hasRequired must be false. + if (codegenModel.requiredVars.isEmpty()) { + codegenModel.hasRequired = false + } + } + + /** + * Private method to investigate all the properties of a models, filter only the [RefProperty] and eventually + * propagate the `x-nullable` vendor config. + */ + private fun propagateXNullableToProperties(model: Model, allDefinitions: MutableMap) { + model.properties + .values + .filterIsInstance(RefProperty::class.java) + .forEach { propagateXNullableVendorExtension(it, allDefinitions) } + } + + /** + * Private method to propagate the `x-nullable` vendor config form the global definitions to the usage. + */ + private fun propagateXNullableVendorExtension( + refProperty: RefProperty, + allDefinitions: MutableMap + ) { + if (allDefinitions[refProperty.simpleRef]?.vendorExtensions?.get(X_NULLABLE) == true) { + refProperty.vendorExtensions[X_NULLABLE] = true + } + } + + /** + * Method to check if a top level definition (array or map) contains an enum that needs to be defined. + * By default those top level definitions will create objects like `List` and `Map`. + * + * This method will check if the [StringProperty] has an enum and attach it as a variable to the [CodegenModel]. + * This will allow us to generate the proper definitions for the enum. + * Furthermore the dataType will be updated to use the Enum type (rather than string) + */ + protected fun checkForEnumsInTopLevel(codegenModel: CodegenModel, model: Model) { + var innerEnum: CodegenProperty? = null + + // Checking if the top level definition is an array with a string property and enum. + if (model is ArrayModel && model.items is StringProperty) { + val items = model.items as StringProperty + if (items.enum != null) { + innerEnum = fromProperty(codegenModel.name, model.items) + } + } + // Checking if the top level definition is a map with a string property and enum. + if (model is ModelImpl && model.additionalProperties is StringProperty) { + val items = model.additionalProperties as StringProperty + if (items.enum != null) { + innerEnum = fromProperty(codegenModel.name, model.additionalProperties) + } + } + if (innerEnum == null) { + // No inner enum found, then you have nothing to do. + return + } + codegenModel.hasEnums = true + codegenModel.vars.add(innerEnum) + codegenModel.dataType = + codegenModel.dataType.replace(defaultStringType(), innerEnum.datatypeWithEnum) + } + + /** + * Method to return the list of Header parameters that we want to suppress from the generated code. + * + * Client code might have a centralized way to handle the headers (Android is attaching them with an OkHttp + * Header Interceptor) and is helpful to remove the header from the endpoints to avoid confusion. + */ + protected fun getHeadersToIgnore(): List { + return try { + val headerList = mutableListOf() + val headerParam = additionalProperties[HEADERS_TO_IGNORE] as? String + if (headerParam != null) { + headerList.addAll(headerParam.split(',')) + } + headerList.toList() + } catch (e: Throwable) { + listOf() + } + } + + /** + * Method to remove the a header parameter from a [CodegenOperation]. + */ + protected fun ignoreHeaderParameter(headerName: String, codegenOperation: CodegenOperation) { + codegenOperation.headerParams.removeAll { + it.baseName!!.contentEquals(headerName) + } + codegenOperation.allParams.removeAll { + it.baseName!!.contentEquals(headerName) + } + + // If we removed the last parameter of the Operation, we should update the `hasMore` flag. + codegenOperation.allParams.lastOrNull()?.hasMore = false + } + + /** + * Resolve the type declaration of a [Property]. + * Please note that this method will recursively resolve all the types. + * For ArrayProperties this will generate a `List of ` + * For MapProperties this will generate a `Map from String to ` + * For other Properties this will resolve the type and evaluate the `X-Nullability` + */ + internal fun resolvePropertyType( + property: Property, + listTypeWrapper: (String, String) -> String = ::listTypeWrapper, + mapTypeWrapper: (String, String) -> String = ::mapTypeWrapper + ): String { + return when (property) { + is ArrayProperty -> { + // Will generate a type like List + listTypeWrapper(getSwaggerType(property), resolvePropertyType(property.items)) + } + is MapProperty -> { + // Will generate a type like Map + mapTypeWrapper(getSwaggerType(property), resolvePropertyType(property.additionalProperties)) + } + // Please note that calling super.getTypeDeclaration() will block the recursion + // and will pick a type from the typeMapping. + // Here we want to evaluate the X-Nullability and eventually annotate the type. + else -> { + val baseType = super.getTypeDeclaration(property) + return if (property.isXNullable()) { + baseType.safeSuffix("?") + } else { + baseType + } + } + } + } + + /** + * Private method to return a dataType for a [CodegenModel] that is an Alias. + * This is useful for populating type for model with 'additionalProperties' at the top level (Maps) + * or `items` at the top level (Arrays). + * Their returned type would be a `Map` or `List`, where `Any?` will be the aliased type. + * + * The method will call [KotlinAndroidGenerator.resolvePropertyType] that will perform a check if the model + * is aliasing to a 'x-nullable' annotated model and compute the proper type (adding a `?` if needed). + * + * ``` + * // e.g. for a not 'x-nullable' additionalProperty type + * typealias myModel = Map + * + * // or this fon a 'x-nullable' additionalProperty type + * typealias myModel = Map + * ``` + */ + internal fun getAliasTypeDeclaration( + codegenModel: CodegenModel, + listTypeWrapper: (String, String) -> String = ::listTypeWrapper, + mapTypeWrapper: (String, String) -> String = ::mapTypeWrapper + ): String? { + + // If the codegenModel has arrayModelType properties here (top level) must alias to a list. + if (codegenModel.isArrayModel) { + val innerProperty = (this.swagger?.definitions?.get(codegenModel.name) as ArrayModel).items + return listTypeWrapper(defaultListType(), resolvePropertyType(innerProperty)) + } + + // If the codegenModel has additional properties here (top level) must alias to a map. + // This method will generate the proper type of the alias. + if (codegenModel.additionalPropertiesType != null) { + val innerProperty = (this.swagger?.definitions?.get(codegenModel.name) as ModelImpl).additionalProperties + return mapTypeWrapper(defaultMapType(), resolvePropertyType(innerProperty)) + } + + return codegenModel.dataType + } + + /** + * Abstract function to create a type for a JSON Array. + * @param listType A List Type (e.g. `List`, `ArrayList`, etc) + * @param innerType The List value Type (e.g. `String`, `Integer`, `Any?`, etc.) + * @return The composed list type (e.g. `List`, `[ String ]`, etc. + */ + protected abstract fun listTypeWrapper(listType: String, innerType: String): String + + /** + * Abstract function to create a type for a JSON Object (A Map from String to values). + * Please note that in JSON Maps have only Strings as keys. + * + * @param mapType A Map Type (e.g. `Map`, `HashMap`, `Dictionary`, etc.) + * @param innerType The Value Type (e.g. `String`, `Integer`, `Any?`, etc.) + * @return The composed map type (e.g. `Map`, `[String: Integer]`, etc. + */ + protected abstract fun mapTypeWrapper(mapType: String, innerType: String): String + + /** + * Abstract function to create a type from a Nullable type. + * @param baseType A type (e.g. `Integer`). + * @return The nullable version of the [baseType] (e.g. `Integer?` for Kotlin) + */ + protected abstract fun nullableTypeWrapper(baseType: String): String + + private fun defaultListType() = typeMapping["list"] ?: "" + + private fun defaultMapType() = typeMapping["map"] ?: "" + + private fun defaultStringType() = typeMapping["string"] ?: "" + + /** + * Checking if the type is marked as XNullable. + */ + internal fun Property.isXNullable() = this.vendorExtensions[X_NULLABLE] == true + + /** + * Checking if the type should be nullable. + * Nullable type are either not required or x-nullable annotated properties. + */ + internal fun Property.isNullable() = !this.required || this.vendorExtensions[X_NULLABLE] == true + + /** + * Checking if the type should be nullable. + * Nullable type are either not required or x-nullable annotated properties. + */ + internal fun CodegenProperty.isNullable() = !this.required || this.vendorExtensions[X_NULLABLE] == true +} diff --git a/plugin/src/main/java/com/yelp/codegen/plugin/CodegenPlugin.kt b/plugin/src/main/java/com/yelp/codegen/plugin/CodegenPlugin.kt new file mode 100644 index 00000000..80e87794 --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/plugin/CodegenPlugin.kt @@ -0,0 +1,140 @@ +package com.yelp.codegen.plugin + +import com.yelp.codegen.main +import org.gradle.api.DefaultTask +import org.gradle.api.plugins.BasePlugin +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Nested +import org.gradle.api.tasks.Optional +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.options.Option +import org.json.JSONException +import org.json.JSONObject +import org.json.JSONTokener +import java.io.File +import java.io.FileInputStream + +const val DEFAULT_PLATFORM = "kotlin" +const val DEFAULT_VERSION = "0.0.0" +const val DEFAULT_NAME = "defaultname" +const val DEFAULT_PACKAGE = "com.codegen.default" +const val DEFAULT_OUTPUT_DIR = "/gen" + +open class GenerateTask : DefaultTask() { + + init { + description = "Run the Swagger Code Generation tool" + group = BasePlugin.BUILD_GROUP + } + + @Input + @Optional + @Option(option = "platform", description = "Configures the platform that is used for generating the code.") + var platform: String? = null + + @Input + @Optional + @Option(option = "packageName", description = "Configures the package name of the resulting code.") + var packageName: String? = null + + @Input + @Optional + @Option(option = "specName", description = "Configures the name of the service for the Swagger Spec.") + var specName: String? = null + + @Input + @Optional + @Option(option = "specVersion", description = "Configures the version of the Swagger Spec.") + var specVersion: String? = null + + @InputFile + @Option(option = "inputFile", description = "Configures path of the Swagger Spec.") + lateinit var inputFile: File + + @OutputDirectory + @Optional + @Option(option = "outputDir", description = "Configures path of the Generated code directory.") + var outputDir: File? = null + + @InputFiles + @Optional + @Option(option = "extraFiles", description = "Configures path of the extra files directory to be added to the Generated code.") + var extraFiles: File? = null + + @Nested + @Option(option = "featureHeaderToRemove", description = "") + var features: FeatureConfiguration? = null + + @TaskAction + fun swaggerGenerate() { + + if (specVersion == null) { + readVersionFromSpecfile(inputFile) + } + val defaultOutputDir = File(project.buildDir, DEFAULT_OUTPUT_DIR) + + println(""" + #################### + Yelp Swagger Codegen + #################### + Platform ${'\t'} ${platform ?: "[ DEFAULT ] $DEFAULT_PLATFORM"} + Package ${'\t'} ${packageName ?: "[ DEFAULT ] $DEFAULT_PACKAGE"} + specName ${'\t'} ${specName ?: "[ DEFAULT ] $DEFAULT_NAME"} + specVers ${'\t'} ${specVersion ?: "[ DEFAULT ] $DEFAULT_VERSION"} + input ${"\t\t"} $inputFile + output ${"\t\t"} ${outputDir ?: "[ DEFAULT ] $defaultOutputDir"} + groupId ${'\t'} ${packageName ?: "[ DEFAULT ] default"} + artifactId ${'\t'} ${packageName ?: "[ DEFAULT ] com.codegen"} + features ${'\t'} ${features?.headersToRemove?.joinToString(", ")?.ifEmpty { "[ EMPTY ]" }} + """.trimIndent()) + + val packageName = packageName ?: DEFAULT_PACKAGE + + val params = mutableListOf() + params.add("-p") + params.add(platform ?: DEFAULT_PLATFORM) + params.add("-s") + params.add(specName ?: DEFAULT_NAME) + params.add("-v") + params.add(specVersion ?: DEFAULT_VERSION) + params.add("-g") + params.add(packageName.substringBeforeLast('.')) + params.add("-a") + params.add(packageName.substringAfterLast('.')) + params.add("-i") + params.add(inputFile.toString()) + params.add("-o") + params.add((outputDir ?: defaultOutputDir).toString()) + + if (true == features?.headersToRemove?.isNotEmpty()) { + params.add("-ignoreheaders") + params.add(features?.headersToRemove?.joinToString(",") ?: "") + } + + // Running the Codegen Main here + main(params.toTypedArray()) + + // Copy over the extra files. + val source = extraFiles + val destin = outputDir + if (source != null && destin != null) { + source.copyRecursively(destin, overwrite = true) + } + } + + private fun readVersionFromSpecfile(specFile: File) { + try { + FileInputStream(specFile).use { + val jsonObject = JSONTokener(it).nextValue() as JSONObject + val version = jsonObject.getJSONObject("info").getString("version") + println("Successfully read version from Swagger Spec file: $version") + specVersion = version + } + } catch (e: JSONException) { + System.err.println("Failed to parse $specFile to read spec version") + } + } +} diff --git a/plugin/src/main/java/com/yelp/codegen/plugin/FeatureConfiguration.kt b/plugin/src/main/java/com/yelp/codegen/plugin/FeatureConfiguration.kt new file mode 100644 index 00000000..e2e10469 --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/plugin/FeatureConfiguration.kt @@ -0,0 +1,11 @@ +package com.yelp.codegen.plugin + +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.Optional + +open class FeatureConfiguration { + + @Input + @Optional + var headersToRemove: Array = arrayOf() +} diff --git a/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTaskConfiguration.kt b/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTaskConfiguration.kt new file mode 100644 index 00000000..361f5d86 --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTaskConfiguration.kt @@ -0,0 +1,18 @@ +package com.yelp.codegen.plugin + +import org.gradle.api.Action +import org.gradle.api.Project +import java.io.File + +open class GenerateTaskConfiguration(project: Project) { + var platform: String? = null + var packageName: String? = null + var specName: String? = null + var specVersion: String? = null + lateinit var inputFile: File + var outputDir: File? = null + var extraFiles: File? = null + var features: FeatureConfiguration = FeatureConfiguration() + + fun features(action: Action) = action.execute(features) +} diff --git a/plugin/src/main/java/com/yelp/codegen/utils/InlineModelResolver.java b/plugin/src/main/java/com/yelp/codegen/utils/InlineModelResolver.java new file mode 100644 index 00000000..0c66af58 --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/utils/InlineModelResolver.java @@ -0,0 +1,495 @@ +package com.yelp.codegen.utils; + +import io.swagger.models.*; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.*; +import io.swagger.util.Json; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * A fork of [{@link io.swagger.codegen.InlineModelResolver} that copies the vendor extensions in + * the resolved definitions. + */ +public class InlineModelResolver { + private Swagger swagger; + private boolean skipMatches; + + private Map addedModels = new HashMap<>(); + private Map generatedSignature = new HashMap<>(); + + public void flatten(Swagger swagger) { + this.swagger = swagger; + + if (swagger.getDefinitions() == null) { + swagger.setDefinitions(new HashMap<>()); + } + + // operations + Map paths = swagger.getPaths(); + Map models = swagger.getDefinitions(); + + if (paths != null) { + for (String pathname : paths.keySet()) { + Path path = paths.get(pathname); + + for (Operation operation : path.getOperations()) { + List parameters = operation.getParameters(); + + if (parameters != null) { + for (Parameter parameter : parameters) { + if (parameter instanceof BodyParameter) { + BodyParameter bp = (BodyParameter) parameter; + if (bp.getSchema() != null) { + Model model = bp.getSchema(); + if (model instanceof ModelImpl) { + ModelImpl obj = (ModelImpl) model; + if (obj.getType() == null + || "object".equals(obj.getType())) { + if (obj.getProperties() != null + && obj.getProperties().size() > 0) { + flattenProperties(obj.getProperties(), pathname); + String modelName = + resolveModelName( + obj.getTitle(), bp.getName()); + bp.setSchema(new RefModel(modelName)); + addGenerated(modelName, model); + swagger.addDefinition(modelName, model); + } + } + } else if (model instanceof ArrayModel) { + ArrayModel am = (ArrayModel) model; + Property inner = am.getItems(); + + if (inner instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) inner; + if (op.getProperties() != null + && op.getProperties().size() > 0) { + flattenProperties(op.getProperties(), pathname); + String modelName = + resolveModelName( + op.getTitle(), bp.getName()); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + RefProperty refProperty = + new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + am.setItems(refProperty); + } else { + RefProperty refProperty = + new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + am.setItems(refProperty); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } + } + } + } + } + } + } + Map responses = operation.getResponses(); + if (responses != null) { + for (String key : responses.keySet()) { + Response response = responses.get(key); + if (response.getSchema() != null) { + Property property = response.getSchema(); + if (property instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) property; + if (op.getProperties() != null + && op.getProperties().size() > 0) { + String modelName = + resolveModelName( + op.getTitle(), "inline_response_" + key); + Model model = modelFromProperty(op, modelName); + String existing = matchGenerated(model); + if (existing != null) { + Property refProperty = + this.makeRefProperty(existing, property); + refProperty.setRequired(op.getRequired()); + response.setSchema(refProperty); + } else { + Property refProperty = + this.makeRefProperty(modelName, property); + refProperty.setRequired(op.getRequired()); + response.setSchema(refProperty); + addGenerated(modelName, model); + swagger.addDefinition(modelName, model); + } + } + } else if (property instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) property; + Property inner = ap.getItems(); + + if (inner instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) inner; + if (op.getProperties() != null + && op.getProperties().size() > 0) { + flattenProperties(op.getProperties(), pathname); + String modelName = + resolveModelName( + op.getTitle(), + "inline_response_" + key); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + Property refProperty = + this.makeRefProperty(existing, op); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); + } else { + Property refProperty = + this.makeRefProperty(modelName, op); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } + } + } else if (property instanceof MapProperty) { + MapProperty mp = (MapProperty) property; + + Property innerProperty = mp.getAdditionalProperties(); + if (innerProperty instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) innerProperty; + if (op.getProperties() != null + && op.getProperties().size() > 0) { + flattenProperties(op.getProperties(), pathname); + String modelName = + resolveModelName( + op.getTitle(), + "inline_response_" + key); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); + } else { + RefProperty refProperty = + new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } + } + } + } + } + } + } + } + } + + // definitions + if (models != null) { + List modelNames = new ArrayList<>(models.keySet()); + for (String modelName : modelNames) { + Model model = models.get(modelName); + if (model instanceof ModelImpl) { + ModelImpl m = (ModelImpl) model; + + Map properties = m.getProperties(); + flattenProperties(properties, modelName); + fixStringModel(m); + } else if (model instanceof ArrayModel) { + ArrayModel m = (ArrayModel) model; + Property inner = m.getItems(); + if (inner instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) inner; + if (op.getProperties() != null && op.getProperties().size() > 0) { + String innerModelName = + resolveModelName(op.getTitle(), modelName + "_inner"); + Model innerModel = modelFromProperty(op, innerModelName); + String existing = matchGenerated(innerModel); + if (existing == null) { + swagger.addDefinition(innerModelName, innerModel); + addGenerated(innerModelName, innerModel); + RefProperty refProperty = new RefProperty(innerModelName); + refProperty.setRequired(op.getRequired()); + m.setItems(refProperty); + } else { + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + m.setItems(refProperty); + } + } + } + } else if (model instanceof ComposedModel) { + ComposedModel m = (ComposedModel) model; + if (m.getChild() != null) { + Map properties = m.getChild().getProperties(); + flattenProperties(properties, modelName); + } + } + } + } + } + + /** + * This function fix models that are string (mostly enum). Before this fix, the example would + * look something like that in the doc: "\"example from def\"" + * + * @param m Model implementation + */ + private void fixStringModel(ModelImpl m) { + if (m.getType() != null && m.getType().equals("string") && m.getExample() != null) { + String example = m.getExample().toString(); + if (example.substring(0, 1).equals("\"") + && example.substring(example.length() - 1).equals("\"")) { + m.setExample(example.substring(1, example.length() - 1)); + } + } + } + + private String resolveModelName(String title, String key) { + if (title == null) { + return uniqueName(key); + } else { + return uniqueName(title); + } + } + + private String matchGenerated(Model model) { + if (this.skipMatches) { + return null; + } + String json = Json.pretty(model); + if (generatedSignature.containsKey(json)) { + return generatedSignature.get(json); + } + return null; + } + + private void addGenerated(String name, Model model) { + generatedSignature.put(Json.pretty(model), name); + } + + private String uniqueName(String key) { + int count = 0; + boolean done = false; + + key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); + // FIXME: a parameter + // Should not be assigned. Also declare the methods parameters as 'final'. + while (!done) { + String name = key; + if (count > 0) { + name = key + "_" + count; + } + if (swagger.getDefinitions() == null) { + return name; + } else if (!swagger.getDefinitions().containsKey(name)) { + return name; + } + count += 1; + } + return key; + } + + private void flattenProperties(Map properties, String path) { + if (properties == null) { + return; + } + Map propsToUpdate = new HashMap<>(); + Map modelsToAdd = new HashMap<>(); + for (String key : properties.keySet()) { + Property property = properties.get(key); + if (property instanceof ObjectProperty + && ((ObjectProperty) property).getProperties() != null + && ((ObjectProperty) property).getProperties().size() > 0) { + + ObjectProperty op = (ObjectProperty) property; + + String modelName = resolveModelName(op.getTitle(), path + "_" + key); + Model model = modelFromProperty(op, modelName); + + String existing = matchGenerated(model); + + if (existing != null) { + RefProperty refProperty = (RefProperty) makeRefProperty(existing, property); + refProperty.setRequired(op.getRequired()); + propsToUpdate.put(key, refProperty); + } else { + RefProperty refProperty = (RefProperty) makeRefProperty(modelName, property); + refProperty.setRequired(op.getRequired()); + propsToUpdate.put(key, refProperty); + modelsToAdd.put(modelName, model); + addGenerated(modelName, model); + swagger.addDefinition(modelName, model); + } + } else if (property instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) property; + Property inner = ap.getItems(); + + if (inner instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) inner; + if (op.getProperties() != null && op.getProperties().size() > 0) { + flattenProperties(op.getProperties(), path); + String modelName = resolveModelName(op.getTitle(), path + "_" + key); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + Property refProperty = makeRefProperty(existing, property); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); + } else { + Property refProperty = makeRefProperty(modelName, property); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } + } + } else if (property instanceof MapProperty) { + MapProperty mp = (MapProperty) property; + Property inner = mp.getAdditionalProperties(); + + if (inner instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) inner; + if (op.getProperties() != null && op.getProperties().size() > 0) { + flattenProperties(op.getProperties(), path); + String modelName = resolveModelName(op.getTitle(), path + "_" + key); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); + } else { + RefProperty refProperty = new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } + } + } + } + if (propsToUpdate.size() > 0) { + for (String key : propsToUpdate.keySet()) { + properties.put(key, propsToUpdate.get(key)); + } + } + for (String key : modelsToAdd.keySet()) { + swagger.addDefinition(key, modelsToAdd.get(key)); + this.addedModels.put(key, modelsToAdd.get(key)); + } + } + + @SuppressWarnings("static-method") + public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") String path) { + String description = object.getDescription(); + String example = null; + + Object obj = object.getExample(); + if (obj != null) { + example = obj.toString(); + } + + Property inner = object.getItems(); + if (inner instanceof ObjectProperty) { + ArrayModel model = new ArrayModel(); + model.setDescription(description); + model.setExample(example); + model.setItems(object.getItems()); + return model; + } + + return null; + } + + private Model modelFromProperty(ObjectProperty object, String path) { + String description = object.getDescription(); + String example = null; + + Object obj = object.getExample(); + if (obj != null) { + example = obj.toString(); + } + String name = object.getName(); + Xml xml = object.getXml(); + Map properties = object.getProperties(); + + ModelImpl model = new ModelImpl(); + model.setDescription(description); + model.setExample(example); + model.setName(name); + model.setXml(xml); + + if (properties != null) { + flattenProperties(properties, path); + model.setProperties(properties); + } + copyVendorExtensions(object, model); + + return model; + } + + @SuppressWarnings("static-method") + public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") String path) { + String description = object.getDescription(); + String example = null; + + Object obj = object.getExample(); + if (obj != null) { + example = obj.toString(); + } + + ArrayModel model = new ArrayModel(); + model.setDescription(description); + model.setExample(example); + model.setItems(object.getAdditionalProperties()); + + return model; + } + + /** + * Make a RefProperty + * + * @param ref new property name + * @param property Property + */ + private Property makeRefProperty(String ref, Property property) { + RefProperty newProperty = new RefProperty(ref); + this.copyVendorExtensions(property, newProperty); + return newProperty; + } + + /** + * Copy vendor extensions from Property to another Property + * + * @param source source property + * @param target target property + */ + private void copyVendorExtensions(Property source, AbstractProperty target) { + Map vendorExtensions = source.getVendorExtensions(); + for (String extName : vendorExtensions.keySet()) { + target.setVendorExtension(extName, vendorExtensions.get(extName)); + } + } + + /** + * Copy vendor extensions from Property to another Property + * + * @param source source property + * @param target target property + */ + private void copyVendorExtensions(Property source, ModelImpl target) { + Map vendorExtensions = source.getVendorExtensions(); + for (String extName : vendorExtensions.keySet()) { + target.setVendorExtension(extName, vendorExtensions.get(extName)); + } + } +} diff --git a/plugin/src/main/java/com/yelp/codegen/utils/KotlinLangUtils.kt b/plugin/src/main/java/com/yelp/codegen/utils/KotlinLangUtils.kt new file mode 100644 index 00000000..9654145a --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/utils/KotlinLangUtils.kt @@ -0,0 +1,178 @@ +package com.yelp.codegen.utils + +import io.swagger.codegen.DefaultCodegen + +object KotlinLangUtils { + + internal val kotlinLanguageSpecificPrimitives = setOf( + "kotlin.Byte", + "kotlin.Short", + "kotlin.Int", + "kotlin.Long", + "kotlin.Float", + "kotlin.Double", + "kotlin.Boolean", + "kotlin.Char", + "kotlin.String", + "kotlin.Array", + "kotlin.collections.List", + "kotlin.collections.Map", + "kotlin.collections.Set" + ) + + // This includes hard reserved words defined by +// https://github.com/JetBrains/kotlin/blob/2593ce73f17f63108392e0d8217bf4ecc1606b96/core/descriptors/src/org/jetbrains/kotlin/renderer/KeywordStringsGenerated.java +// as well as keywords from https://kotlinlang.org/docs/reference/keyword-reference.html + internal val kotlinReservedWords = setOf( + "abstract", + "annotation", + "as", + "break", + "case", + "catch", + "class", + "companion", + "const", + "constructor", + "continue", + "crossinline", + "data", + "delegate", + "do", + "else", + "enum", + "external", + "false", + "final", + "finally", + "for", + "fun", + "if", + "in", + "infix", + "init", + "inline", + "inner", + "interface", + "internal", + "is", + "it", + "lateinit", + "lazy", + "noinline", + "null", + "object", + "open", + "operator", + "out", + "override", + "package", + "private", + "protected", + "public", + "reified", + "return", + "sealed", + "super", + "suspend", + "tailrec", + "this", + "throw", + "true", + "try", + "typealias", + "typeof", + "val", + "var", + "vararg", + "when", + "while" + ) + + internal val kotlinDefaultIncludes = setOf( + "kotlin.Byte", + "kotlin.Short", + "kotlin.Int", + "kotlin.Long", + "kotlin.Float", + "kotlin.Double", + "kotlin.Boolean", + "kotlin.Char", + "kotlin.Array", + "kotlin.String", + "kotlin.collections.List", + "kotlin.collections.Set", + "kotlin.collections.Map" + ) + + internal val kotlinTypeMapping = mapOf( + "string" to "String", + "boolean" to "Boolean", + "integer" to "Int", + "float" to "Float", + "long" to "Long", + "double" to "Double", + "number" to "BigDecimal", + "date" to "LocalDate", + "DateTime" to "ZonedDateTime", + "date-time" to "ZonedDateTime", + "file" to "File", + "array" to "List", + "list" to "List", + "map" to "Map", + "object" to "Map", + "binary" to "List" + ) + + internal val kotlinInstantiationTypes = mapOf( + "array" to "listOf", + "list" to "listOf", + "map" to "mapOf" + ) + + internal val kotlinImportMapping = mapOf( + "Boolean" to "kotlin.Boolean", + "String" to "kotlin.String", + "Int" to "kotlin.Int", + "Float" to "kotlin.Float", + "Long" to "kotlin.Long", + "Double" to "kotlin.Double", + "BigDecimal" to "java.math.BigDecimal", + "LocalDate" to "org.threeten.bp.LocalDate", + "ZonedDateTime" to "org.threeten.bp.ZonedDateTime", + "File" to "java.io.File", + "List" to "kotlin.collections.List", + "List" to "kotlin.collections.List", + "Map" to "kotlin.collections.Map", + "Map" to "kotlin.collections.Map", + "Timestamp" to "java.sql.Timestamp", + "UUID" to "java.util.UUID" + ) +} + +/** + * Sanitize against Kotlin specific naming conventions, which may differ from those required + * by [DefaultCodegen.sanitizeName]. + * + * Receiver is the string to be sanitize + * @return sanitized string + */ +internal fun String.sanitizeKotlinSpecificNames(replacements: Map): String { + var word = this + for ((key, value) in replacements) { + word = word.replace("\\Q$key\\E".toRegex(), value) + } + + // Fallback, replace unknowns with underscore. + word = word.replace("\\W+".toRegex(), "_") + if (word.matches("\\d.*".toRegex())) { + word = "_$word" + } + + // _, __, and ___ are reserved in Kotlin. Treat all names with only underscores consistently, regardless of count. + if (word.matches("^_+$".toRegex())) { + word = word.replace("\\Q_\\E".toRegex(), "Underscore") + } + + return word +} diff --git a/plugin/src/main/java/com/yelp/codegen/utils/StringUtils.kt b/plugin/src/main/java/com/yelp/codegen/utils/StringUtils.kt new file mode 100644 index 00000000..92806646 --- /dev/null +++ b/plugin/src/main/java/com/yelp/codegen/utils/StringUtils.kt @@ -0,0 +1,27 @@ +@file:JvmName("StringUtils") +package com.yelp.codegen.utils + +private const val ANSI_RED = "\u001B[31m" +private const val ANSI_RESET = "\u001B[0m" + +fun String.toCamelCase(): String { + val split = this.split(Regex("[ _]")).map { it.split(Regex("(?=\\p{Upper})")) }.flatten() + return split.map { it.toLowerCase() }.mapIndexed { index, subString -> + if (index == 0) { + subString + } else { + subString.capitalize() + } + }.joinToString("") +} + +fun String.toPascalCase(): String { + return this.toCamelCase().capitalize() +} + +fun String.safeSuffix(suffix: String) = + if (!this.endsWith(suffix)) "$this$suffix" else this + +fun String.red(): String { + return "$ANSI_RED${this}$ANSI_RESET" +} diff --git a/plugin/src/main/kotlin/com/yelp/codegen/plugin.gradle.kts b/plugin/src/main/kotlin/com/yelp/codegen/plugin.gradle.kts new file mode 100644 index 00000000..da3af16a --- /dev/null +++ b/plugin/src/main/kotlin/com/yelp/codegen/plugin.gradle.kts @@ -0,0 +1,19 @@ +package com.yelp.codegen + +import com.yelp.codegen.plugin.GenerateTask +import com.yelp.codegen.plugin.GenerateTaskConfiguration + +val config = extensions.create("generateSwagger", GenerateTaskConfiguration::class.java, project) + +tasks { + register("generateSwagger") { + platform = config.platform + packageName = config.packageName + specName = config.specName + specVersion = config.specVersion + inputFile = config.inputFile + outputDir = config.outputDir + extraFiles = config.extraFiles + features = config.features + } +} diff --git a/plugin/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/plugin/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig new file mode 100644 index 00000000..13a488d1 --- /dev/null +++ b/plugin/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -0,0 +1 @@ +com.yelp.codegen.KotlinGenerator diff --git a/plugin/src/main/resources/kotlin/data_class.mustache b/plugin/src/main/resources/kotlin/data_class.mustache new file mode 100644 index 00000000..8cdc29ed --- /dev/null +++ b/plugin/src/main/resources/kotlin/data_class.mustache @@ -0,0 +1,23 @@ +/** + * {{{description}}} +{{#vars}} + * @property {{{name}}} {{description}} +{{/vars}} + */ +{{#hasVars}}data {{/hasVars}}class {{classname}} {{#hasVars}}( +{{#requiredVars}} +{{>data_class_req_var}}{{^-last}}, +{{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, +{{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{>data_class_opt_var}}{{^-last}}, +{{/-last}}{{/optionalVars}} +){{#hasEnums}} { +{{#vars}} +{{#isEnum}} + /** + * {{{description}}} + * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} + */ + enum class {{enumName}}(val value: {{complexType}}){ {{#allowableValues}}{{#enumVars}} + @Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}}{{/-last}}{{/enumVars}}{{/allowableValues}} + } +{{/isEnum}}{{/vars}}}{{/hasEnums}}{{/hasVars}} diff --git a/plugin/src/main/resources/kotlin/data_class_opt_var.mustache b/plugin/src/main/resources/kotlin/data_class_opt_var.mustache new file mode 100644 index 00000000..7078f4c8 --- /dev/null +++ b/plugin/src/main/resources/kotlin/data_class_opt_var.mustache @@ -0,0 +1 @@ + @Json(name = "{{{baseName}}}") @field:Json(name = "{{{baseName}}}") {{#vendorExtensions.x-nullable}}@XNullable {{/vendorExtensions.x-nullable}}var {{{name}}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}} = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file diff --git a/plugin/src/main/resources/kotlin/data_class_req_var.mustache b/plugin/src/main/resources/kotlin/data_class_req_var.mustache new file mode 100644 index 00000000..94994bdb --- /dev/null +++ b/plugin/src/main/resources/kotlin/data_class_req_var.mustache @@ -0,0 +1 @@ + @Json(name = "{{{baseName}}}") @field:Json(name = "{{{baseName}}}") var {{{name}}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}} \ No newline at end of file diff --git a/plugin/src/main/resources/kotlin/enum_class.mustache b/plugin/src/main/resources/kotlin/enum_class.mustache new file mode 100644 index 00000000..6a49c5a4 --- /dev/null +++ b/plugin/src/main/resources/kotlin/enum_class.mustache @@ -0,0 +1,7 @@ +/** +* {{{description}}} +* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +*/ +enum class {{classname}}(val value: {{dataType}}){ +{{#allowableValues}}{{#enumVars}} @Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} +{{/enumVars}}{{/allowableValues}}} diff --git a/plugin/src/main/resources/kotlin/file_header.mustache b/plugin/src/main/resources/kotlin/file_header.mustache new file mode 100644 index 00000000..13c90449 --- /dev/null +++ b/plugin/src/main/resources/kotlin/file_header.mustache @@ -0,0 +1,5 @@ +/** + * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: {{{appName}}} + * + * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen + */ diff --git a/plugin/src/main/resources/kotlin/model.mustache b/plugin/src/main/resources/kotlin/model.mustache new file mode 100644 index 00000000..01ad7762 --- /dev/null +++ b/plugin/src/main/resources/kotlin/model.mustache @@ -0,0 +1,11 @@ +{{>file_header}} +package {{modelPackage}} + +{{#imports}}import {{import}} +{{/imports}} + +{{#models}} +{{#model}} +{{#isAlias}}{{>type_alias}}{{/isAlias}}{{^isAlias}}{{#isEnum}}{{>enum_class}}{{/isEnum}}{{^isEnum}}{{>data_class}}{{/isEnum}}{{/isAlias}} +{{/model}} +{{/models}} diff --git a/plugin/src/main/resources/kotlin/retrofit2/api.mustache b/plugin/src/main/resources/kotlin/retrofit2/api.mustache new file mode 100644 index 00000000..8fa8601e --- /dev/null +++ b/plugin/src/main/resources/kotlin/retrofit2/api.mustache @@ -0,0 +1,49 @@ +{{>file_header}} +package {{package}} + +import okhttp3.RequestBody + +{{#imports}}import {{import}} +{{/imports}} + +{{#operations}} +@JvmSuppressWildcards +interface {{classname}} { + {{#operation}} + /**{{#summary}} {{{newline}}} * {{{summary}}}{{/summary}}{{#notes}}{{{newline}}} * {{{
}}}{{{notes}}}{{/notes}} + * The endpoint is owned by {{{vendorExtensions.x-team-owners}}}{{^vendorExtensions.x-team-owners}}{{service_name}} service owner{{/vendorExtensions.x-team-owners}} +{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +{{/allParams}} +{{#externalDocs}} + * {{description}} + * @see [{{url}}"][{{summary}} Documentation] +{{/externalDocs}} + */ + {{#formParams}} + {{#-first}} + {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}} + {{/-first}} + {{/formParams}} + {{^formParams}} + {{#prioritizedContentTypes}} + {{#-first}} + @Headers({ + "Content-Type:{{{mediaType}}}" + }) + {{/-first}} + {{/prioritizedContentTypes}} + {{/formParams}} + @Headers({{#vendorExtensions.x-operation-id}}{{{newline}}} "X-Operation-ID: {{vendorExtensions.x-operation-id}}"{{/vendorExtensions.x-operation-id}}{{^formParams}}{{#prioritizedContentTypes}}{{#-first}}, + "Content-Type:{{{mediaType}}}"{{/-first}}{{/prioritizedContentTypes}}{{/formParams}} + ) + @{{httpMethod}}("{{{path}}}"){{#isDeprecated}} + @Deprecated(message = "Deprecated"){{/isDeprecated}} + fun {{operationId}}({{^allParams}}){{/allParams}} + {{#allParams}}{{>retrofit2/queryParams}}{{>retrofit2/pathParams}}{{>retrofit2/headerParams}}{{>retrofit2/bodyParams}}{{>retrofit2/formParams}}{{#hasMore}}, + {{/hasMore}}{{^hasMore}} + ){{/hasMore}}{{/allParams}}: {{{returnType}}} + + {{/operation}} +} +{{/operations}} diff --git a/plugin/src/main/resources/kotlin/retrofit2/bodyParams.mustache b/plugin/src/main/resources/kotlin/retrofit2/bodyParams.mustache new file mode 100644 index 00000000..c771bcd7 --- /dev/null +++ b/plugin/src/main/resources/kotlin/retrofit2/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@retrofit2.http.Body {{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{/isBodyParam}} \ No newline at end of file diff --git a/plugin/src/main/resources/kotlin/retrofit2/formParams.mustache b/plugin/src/main/resources/kotlin/retrofit2/formParams.mustache new file mode 100644 index 00000000..49b48c29 --- /dev/null +++ b/plugin/src/main/resources/kotlin/retrofit2/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{paramName}}: {{{dataType}}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") {{paramName}}: RequestBody{{^required}}?{{/required}} {{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/plugin/src/main/resources/kotlin/retrofit2/headerParams.mustache b/plugin/src/main/resources/kotlin/retrofit2/headerParams.mustache new file mode 100644 index 00000000..c31a6722 --- /dev/null +++ b/plugin/src/main/resources/kotlin/retrofit2/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@retrofit2.http.Header("{{baseName}}") {{paramName}}: {{{dataType}}}{{/isHeaderParam}} \ No newline at end of file diff --git a/plugin/src/main/resources/kotlin/retrofit2/pathParams.mustache b/plugin/src/main/resources/kotlin/retrofit2/pathParams.mustache new file mode 100644 index 00000000..4cfd5f0c --- /dev/null +++ b/plugin/src/main/resources/kotlin/retrofit2/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@retrofit2.http.Path("{{baseName}}") {{paramName}}: {{{dataType}}}{{/isPathParam}} \ No newline at end of file diff --git a/plugin/src/main/resources/kotlin/retrofit2/queryParams.mustache b/plugin/src/main/resources/kotlin/retrofit2/queryParams.mustache new file mode 100644 index 00000000..1ceefb35 --- /dev/null +++ b/plugin/src/main/resources/kotlin/retrofit2/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@retrofit2.http.Query("{{baseName}}") {{#collectionFormat}}{{^isCollectionFormatMulti}}@{{{collectionFormat.toUpperCase}}} {{/isCollectionFormatMulti}}{{/collectionFormat}}{{paramName}}: {{{dataType}}}{{/isQueryParam}} \ No newline at end of file diff --git a/plugin/src/main/resources/kotlin/tools/CollectionFormatConverterFactory.kt.mustache b/plugin/src/main/resources/kotlin/tools/CollectionFormatConverterFactory.kt.mustache new file mode 100644 index 00000000..057c5add --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/CollectionFormatConverterFactory.kt.mustache @@ -0,0 +1,32 @@ +package {{packageName}}.tools + +import retrofit2.Converter +import retrofit2.Retrofit +import java.lang.reflect.Type + +internal class CollectionFormatConverterFactory : Converter.Factory() { + + override fun stringConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter<*, String>? { + val rawType = getRawType(type) + if (rawType == String::class.java || rawType == List::class.java) + annotations.forEach { + when (it) { + is CSV -> return CollectionFormatConverter(",") + is SSV -> return CollectionFormatConverter(" ") + is TSV -> return CollectionFormatConverter("\t") + is PIPES -> return CollectionFormatConverter("|") + } + } + return null + } + + private class CollectionFormatConverter(private val separator: String) : Converter { + override fun convert(value: Any): String { + when (value) { + is String -> return value + is List<*> -> return value.joinToString(separator) + } + throw RuntimeException("Unsupported type") + } + } +} diff --git a/plugin/src/main/resources/kotlin/tools/CollectionFormats.kt.mustache b/plugin/src/main/resources/kotlin/tools/CollectionFormats.kt.mustache new file mode 100644 index 00000000..966a7bac --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/CollectionFormats.kt.mustache @@ -0,0 +1,20 @@ +package {{packageName}}.tools + +@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER) +@Retention(AnnotationRetention.RUNTIME) +annotation class CSV + + +@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER) +@Retention(AnnotationRetention.RUNTIME) +annotation class SSV + + +@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER) +@Retention(AnnotationRetention.RUNTIME) +annotation class TSV + + +@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER) +@Retention(AnnotationRetention.RUNTIME) +annotation class PIPES diff --git a/plugin/src/main/resources/kotlin/tools/EnumToValueConverterFactory.kt.mustache b/plugin/src/main/resources/kotlin/tools/EnumToValueConverterFactory.kt.mustache new file mode 100644 index 00000000..fd584768 --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/EnumToValueConverterFactory.kt.mustache @@ -0,0 +1,34 @@ +package {{packageName}}.tools + +import com.squareup.moshi.Json +import retrofit2.Converter +import retrofit2.Retrofit +import java.lang.reflect.Type + +internal class EnumToValueConverterFactory : Converter.Factory() { + + private val enumConverter = EnumToValueConverter() + + override fun stringConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter<*, String>? { + return if (type is Class<*> && type.isEnum) { + enumConverter + } else { + null + } + } + + internal class EnumToValueConverter : Converter { + override fun convert(enum: Any): String? { + val enumName = (enum as Enum<*>).name + val jsonAnnotation : Json? = enum.javaClass.getField(enumName).getAnnotation(Json::class.java) + + // Checking if the Enum is annotated with @Json to get the name. + // If not, fallback to enum default (.toString()) + return if (jsonAnnotation != null) { + jsonAnnotation.name + } else { + enum.toString() + } + } + } +} diff --git a/plugin/src/main/resources/kotlin/tools/GeneratedCodeConverters.kt.mustache b/plugin/src/main/resources/kotlin/tools/GeneratedCodeConverters.kt.mustache new file mode 100644 index 00000000..8afd2696 --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/GeneratedCodeConverters.kt.mustache @@ -0,0 +1,39 @@ +package {{packageName}}.tools + +import com.squareup.moshi.Moshi +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import retrofit2.Converter +import retrofit2.converter.moshi.MoshiConverterFactory + + +object GeneratedCodeConverters { + private val moshi = Moshi.Builder() + .add(XNullableAdapterFactory()) + .add(KotlinJsonAdapterFactory()) + .add(TypesAdapterFactory()) + .build() + + /** + * Creates everything needed for retrofit to make it work with the client lib, including a + * [Moshi] instance. If you want to use your own instance of moshi, use + * converterFactory(moshi) instead, and add [XNullableAdapterFactory], [KotlinJsonAdapterFactory] and + * [TypesAdapterFactory] to your moshi builder (in a similar way how we are instantiating the `moshi` field here). + */ + @JvmStatic + fun converterFactory(): Converter.Factory { + return WrapperConverterFactory( + CollectionFormatConverterFactory(), + EnumToValueConverterFactory(), + MoshiConverterFactory.create(moshi) + ) + } + + @JvmStatic + fun converterFactory(moshi: Moshi): Converter.Factory { + return WrapperConverterFactory( + CollectionFormatConverterFactory(), + EnumToValueConverterFactory(), + MoshiConverterFactory.create(moshi) + ) + } +} diff --git a/plugin/src/main/resources/kotlin/tools/TypesAdapters.kt.mustache b/plugin/src/main/resources/kotlin/tools/TypesAdapters.kt.mustache new file mode 100644 index 00000000..aec32665 --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/TypesAdapters.kt.mustache @@ -0,0 +1,90 @@ +package {{packageName}}.tools + +import com.squareup.moshi.JsonAdapter +import com.squareup.moshi.JsonReader +import com.squareup.moshi.JsonWriter +import com.squareup.moshi.Moshi +import com.squareup.moshi.internal.Util +import org.threeten.bp.LocalDate +import org.threeten.bp.ZonedDateTime +import org.threeten.bp.LocalDateTime +import org.threeten.bp.DateTimeException +import org.threeten.bp.ZoneId +import org.threeten.bp.format.DateTimeFormatter +import java.lang.reflect.Type +import java.math.BigDecimal + +/** + * Moshi Factory to handle all the custom types we want to support, + * such as [LocalDate], [ZonedDateTime], [BigDecimal]. + */ +internal class TypesAdapterFactory : JsonAdapter.Factory { + private val types = mapOf>( + LocalDate::class.java to LocalDateAdapter(), + ZonedDateTime::class.java to ZonedDateTimeAdapter(), + BigDecimal::class.java to BigDecimalJsonAdapter() + ) + + override fun create(type: Type, annotations: MutableSet, moshi: Moshi): JsonAdapter<*>? { + if (annotations.isEmpty()) { + for (targetType in types.keys) { + if (Util.typesMatch(type, targetType)) return types[targetType] + } + } + return null + } +} + +/** + * Util Abstract [JsonAdapter] to support Parsing of `null` values for types annotated + * with [XNullable]. This adapter will check if the next token on the JSON reader is a `null` and + * return it. Otherwise will invoke the `fromNonNullString` abstract function. + */ +internal abstract class XNullableJsonAdapter : JsonAdapter() { + + abstract fun fromNonNullString(nextString: String) : T + + override fun fromJson(reader: JsonReader): T? { + return if (reader.peek() != JsonReader.Token.NULL) { + fromNonNullString(reader.nextString()) + } else { + reader.nextNull() + null + } + } +} + +internal class LocalDateAdapter : XNullableJsonAdapter() { + private val formatter = DateTimeFormatter.ISO_LOCAL_DATE + + override fun fromNonNullString(nextString: String) : LocalDate = LocalDate.parse(nextString, formatter) + + override fun toJson(writer: JsonWriter?, value: LocalDate?) { + value?.let { writer?.value(it.format(formatter)) } + } +} + +internal class ZonedDateTimeAdapter : XNullableJsonAdapter() { + private val formatter = DateTimeFormatter.ISO_DATE_TIME + + override fun fromNonNullString(nextString: String): ZonedDateTime { + return try { + ZonedDateTime.parse(nextString, formatter) + } catch (parseException : DateTimeException) { + val localDateTime = LocalDateTime.parse(nextString, formatter) + localDateTime.atZone(ZoneId.of("Z")) + } + } + + override fun toJson(writer: JsonWriter?, value: ZonedDateTime?) { + value?.let { writer?.value(it.format(formatter)) } + } +} + +internal class BigDecimalJsonAdapter : XNullableJsonAdapter() { + override fun fromNonNullString(nextString: String) = BigDecimal(nextString) + + override fun toJson(writer: JsonWriter?, value: BigDecimal?) { + value?.let { writer?.value(it) } + } +} diff --git a/plugin/src/main/resources/kotlin/tools/WrapperConverterFactory.kt.mustache b/plugin/src/main/resources/kotlin/tools/WrapperConverterFactory.kt.mustache new file mode 100644 index 00000000..825dc225 --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/WrapperConverterFactory.kt.mustache @@ -0,0 +1,45 @@ +package {{packageName}}.tools + +import okhttp3.RequestBody +import okhttp3.ResponseBody +import retrofit2.Converter +import retrofit2.Retrofit +import java.lang.reflect.Type + +internal class WrapperConverterFactory(private vararg val factories: Converter.Factory) : Converter.Factory() { + + override fun responseBodyConverter(type: Type, + annotations: Array, + retrofit: Retrofit): Converter? { + return factories.mapFirstNonNull { + it.responseBodyConverter(type, annotations, retrofit) + } + } + + override fun requestBodyConverter(type: Type, + parameterAnnotations: Array, + methodAnnotations: Array, + retrofit: Retrofit): Converter<*, RequestBody>? { + return factories.mapFirstNonNull { + it.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit) + } + } + + override fun stringConverter(type: Type, + annotations: Array, + retrofit: Retrofit): Converter<*, String>? { + return factories.mapFirstNonNull { + it.stringConverter(type, annotations, retrofit) + } + } + + private inline fun Array.mapFirstNonNull(transform: (T) -> R?): R? { + for (element in this) { + val transformed = transform(element) + if (transformed != null) { + return transformed + } + } + return null + } +} diff --git a/plugin/src/main/resources/kotlin/tools/XNullable.kt.mustache b/plugin/src/main/resources/kotlin/tools/XNullable.kt.mustache new file mode 100644 index 00000000..270b5ef9 --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/XNullable.kt.mustache @@ -0,0 +1,13 @@ +package {{packageName}}.tools + +import com.squareup.moshi.JsonQualifier + +/** + * Marks an optional variable that will be forcibly serialized as "null" when being transformed + * to json. (By default, an optional variable is omitted from the output json string, + * for optimisation purposes.) + */ +@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER) +@Retention(AnnotationRetention.RUNTIME) +@JsonQualifier +annotation class XNullable diff --git a/plugin/src/main/resources/kotlin/tools/XNullableAdapterFactory.kt.mustache b/plugin/src/main/resources/kotlin/tools/XNullableAdapterFactory.kt.mustache new file mode 100644 index 00000000..2e7d4e4f --- /dev/null +++ b/plugin/src/main/resources/kotlin/tools/XNullableAdapterFactory.kt.mustache @@ -0,0 +1,50 @@ +package {{packageName}}.tools + +import com.squareup.moshi.JsonAdapter +import com.squareup.moshi.JsonReader +import com.squareup.moshi.JsonWriter +import com.squareup.moshi.Moshi +import java.lang.reflect.Type + +internal class XNullableAdapterFactory : JsonAdapter.Factory { + override fun create(type: Type, annotations: MutableSet, moshi: Moshi): JsonAdapter<*>? { + if (annotations.any { it is XNullable }) { + return object : JsonAdapter() { + override fun fromJson(reader: JsonReader): Any? { + return if (reader.peek() != JsonReader.Token.NULL) { + val nextAdapter = moshi.nextAdapter( + this@XNullableAdapterFactory, + type, + annotations.removeXNullableAnnotation() + ) + nextAdapter?.fromJson(reader) + } else { + reader.nextNull() + } + } + + override fun toJson(writer: JsonWriter, value: Any?) { + if (value == null) { + val serializeNulls = writer.serializeNulls + writer.serializeNulls = true + writer.nullValue() + writer.serializeNulls = serializeNulls + } else { + val nextAdapter = moshi.nextAdapter( + this@XNullableAdapterFactory, + type, + annotations.removeXNullableAnnotation() + ) + nextAdapter?.toJson(writer, value) + } + } + + } + } + return null + } + + private fun Set.removeXNullableAnnotation():MutableSet{ + return this.filter { it !is XNullable }.toMutableSet() + } +} diff --git a/plugin/src/main/resources/kotlin/type_alias.mustache b/plugin/src/main/resources/kotlin/type_alias.mustache new file mode 100644 index 00000000..6361275e --- /dev/null +++ b/plugin/src/main/resources/kotlin/type_alias.mustache @@ -0,0 +1,13 @@ +{{#description}}/** + * {{{description}}} + */{{/description}} +typealias {{classname}} = {{{dataType}}} +{{#hasEnums}}{{#vars}} +/** + * {{{description}}} + * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} + */ +enum class {{enumName}}(val value: String) { + {{#allowableValues}}{{#enumVars}}@Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}}{{/-last}}{{/enumVars}}{{/allowableValues}} +} +{{/vars}}{{/hasEnums}} diff --git a/sample-groovy-android/.gitignore b/sample-groovy-android/.gitignore new file mode 100644 index 00000000..d7b839b5 --- /dev/null +++ b/sample-groovy-android/.gitignore @@ -0,0 +1 @@ +/src/main/java diff --git a/sample-groovy-android/build.gradle b/sample-groovy-android/build.gradle new file mode 100644 index 00000000..d4e29736 --- /dev/null +++ b/sample-groovy-android/build.gradle @@ -0,0 +1,64 @@ +buildscript { + repositories { + mavenLocal() + gradlePluginPortal() + google() + mavenCentral() + jcenter() + } + + dependencies { + classpath "com.android.tools.build:gradle:3.2.1" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.20" + classpath "com.yelp.codegen:plugin:1.0.0" + } +} + +apply plugin: "com.android.library" +apply plugin: "kotlin-android" +apply plugin: "com.yelp.codegen.plugin" + +android { + compileSdkVersion = 28 + defaultConfig { + minSdkVersion = 21 + targetSdkVersion = 28 + versionCode = 1 + versionName = "1.0" + } +} + +dependencies { + // Kotlin + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.11" + implementation "org.jetbrains.kotlin:kotlin-reflect:1.3.11" + + // Moshi + implementation "com.squareup.moshi:moshi:1.8.0" + implementation "com.squareup.moshi:moshi-adapters:1.8.0" + implementation "com.squareup.moshi:moshi-kotlin:1.8.0" + implementation "com.squareup.retrofit2:converter-moshi:2.5.0" + + // Date Support + implementation "com.jakewharton.threetenabp:threetenabp:1.1.1" + + // RxJava + implementation "io.reactivex.rxjava2:rxjava:2.2.4" + implementation "io.reactivex.rxjava2:rxandroid:2.1.0" +} + +generateSwagger { + platform = "kotlin" + packageName = "com.yelp.codegen.integrations" + specName = "integration" + specVersion = "1.0.0" + inputFile = file("../sample_specs.json") + outputDir = file("./src/main/java/") + features { + headersToRemove = ["Accept-Language"] + } +} + +repositories { + mavenCentral() +} diff --git a/sample-groovy-android/src/main/AndroidManifest.xml b/sample-groovy-android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..574a3c27 --- /dev/null +++ b/sample-groovy-android/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + diff --git a/sample-kotlin-android/.gitignore b/sample-kotlin-android/.gitignore new file mode 100644 index 00000000..d7b839b5 --- /dev/null +++ b/sample-kotlin-android/.gitignore @@ -0,0 +1 @@ +/src/main/java diff --git a/sample-kotlin-android/build.gradle.kts b/sample-kotlin-android/build.gradle.kts new file mode 100644 index 00000000..cd05fe2c --- /dev/null +++ b/sample-kotlin-android/build.gradle.kts @@ -0,0 +1,50 @@ +plugins { + id("com.android.library") version "3.2.1" + kotlin("android") version "1.3.20" + id("com.yelp.codegen.plugin") version "1.0.0" +} + +android { + compileSdkVersion(28) + defaultConfig { + minSdkVersion(21) + targetSdkVersion(28) + versionCode = 1 + versionName = "1.0" + } +} + +dependencies { + // Kotlin + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.11") + implementation("org.jetbrains.kotlin:kotlin-reflect:1.3.11") + + // Moshi + implementation("com.squareup.moshi:moshi:1.8.0") + implementation("com.squareup.moshi:moshi-adapters:1.8.0") + implementation("com.squareup.moshi:moshi-kotlin:1.8.0") + implementation("com.squareup.retrofit2:converter-moshi:2.5.0") + + // Date Support + implementation("com.jakewharton.threetenabp:threetenabp:1.1.1") + + // RxJava + implementation("io.reactivex.rxjava2:rxjava:2.2.4") + implementation("io.reactivex.rxjava2:rxandroid:2.1.0") +} + +generateSwagger { + platform = "kotlin" + packageName = "com.yelp.codegen.samples" + specName = "sample_specs" + specVersion = "1.0.0" + inputFile = file("../sample_specs.json") + outputDir = file("./src/main/java/") + features { + headersToRemove = arrayOf("Accept-Language") + } +} + +repositories { + mavenCentral() +} diff --git a/sample-kotlin-android/src/main/AndroidManifest.xml b/sample-kotlin-android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..574a3c27 --- /dev/null +++ b/sample-kotlin-android/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + diff --git a/sample_specs.json b/sample_specs.json new file mode 100644 index 00000000..68ca89a9 --- /dev/null +++ b/sample_specs.json @@ -0,0 +1,74 @@ +{ + "definitions": { + "empty_model": { + "type": "object" + }, + "property_model": { + "properties": { + "enum_property": { + "enum": [ + "VALUE2", + "VALUE1" + ], + "type": "string" + }, + "string_property": { + "type": "string" + } + }, + "type": "object" + } + }, + "info": { + "title": "Specs used as a sample for the generator.", + "version": "1.2.3" + }, + "paths": { + "/empty_endpoint": { + "get": { + "operationId": "get_empty_endpoint", + "responses": { + "200": { + "description": "", + "schema": { + "$ref": "#/definitions/empty_model" + } + } + }, + "summary": "Just an empty endpoint", + "tags": [ + "resource" + ] + } + }, + "/property_endpoint/{property_format}": { + "get": { + "operationId": "get_property_endpoint", + "parameters": [ + { + "in": "path", + "name": "property_format", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "", + "schema": { + "$ref": "#/definitions/property_model" + } + } + }, + "summary": "Just a simple endpoint", + "tags": [ + "resource" + ] + } + } + }, + "produces": [ + "application/json" + ], + "swagger": "2.0" +} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..48bbed45 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenLocal() + mavenCentral() + google() + jcenter() + } + resolutionStrategy { + eachPlugin { + if ("com.android" in requested.id.id) { + useModule("com.android.tools.build:gradle:${requested.version}") + } + } + } +} + +include(":plugin", ":sample-kotlin-android", ":sample-groovy-android")