[meta] Support Kotlin meta generator (#4156)

* [meta] Support Kotlin meta generator

* Guard against automatic scripts (assumptions for this script are not fulfilled by some CI which run "run all" type scripts)
This commit is contained in:
Jim Schubert 2019-11-09 10:47:55 -05:00 committed by GitHub
parent db729be7df
commit 357f6caed5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 1451 additions and 1 deletions

52
bin/meta-codegen-kotlin.sh Executable file
View File

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

View File

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

View File

@ -0,0 +1,60 @@
# {{kebabName}}-openapi-generator
## Requirements
* Gradle 5.x
* Java 8+
## Getting Started
* Initialize the gradle wrapper:
```bash
gradle wrapper --gradle-version 5.6.2
```
* Modify the codegen class and associated templates
* Compile with `./gradlew standalone`
* Verify:
```bash
java -jar build/libs/{{kebabName}}-openapi-generator-standalone.jar config-help -g {{name}}
```
## Building
### Standalone
As seen in "Getting Started", the generator may be built as a standalone customized version of OpenAPI Generator's CLI. This may be the simplest option for developers who are unfamiliar with working in the JVM. Please be aware of any licensing concerns before distributing this "uber-jar".
To build as a standalone, run:
```bash
./gradlew standalone
```
To list generators via OpenAPI Generator CLI:
```bash
java -jar build/libs/{{kebabName}}-openapi-generator-standalone.jar list --include all
```
### ShadowJar
This generator supports building as a lightweight "fat-jar". This option includes Kotlin or any other `implementation` dependencies you'll add. This will simplify publishing if your generator has many dependencies.
To build as a shadowJar, run:
```bash
./gradlew shadowJar
```
To list generators via OpenAPI Generator CLI, you must refer to the CLI jar explicitly. We add a custom copy task which includes the CLI jar in the build output directory:
```bash
java -cp build/libs/openapi-generator-cli-4.1.3.jar:build/libs/{{kebabName}}-openapi-generator-1.0-SNAPSHOT-all.jar org.openapitools.codegen.OpenAPIGenerator list
```
Notice that this command _must_ pass classpath via `-cp` and include OpenAPI Generator CLI as well as the artifact built from this project. Also notice that the manifest class must be passed explicitly as `org.openapitools.codegen.OpenAPIGenerator`.
## See Also
* [Customization docs](https://openapi-generator.tech/docs/customization)
* [Templating docs](https://openapi-generator.tech/docs/templating)

View File

@ -0,0 +1,62 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.3.41"
id("com.github.johnrengelman.shadow") version("5.0.0")
}
group = "org.openapitools"
version = "1.0-SNAPSHOT"
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
val openapiGeneratorVersion = "4.1.3"
implementation(kotlin("stdlib-jdk8"))
implementation("org.openapitools:openapi-generator:$openapiGeneratorVersion")
runtime("org.openapitools:openapi-generator-cli:$openapiGeneratorVersion")
testImplementation("org.junit.jupiter:junit-jupiter:5.5.2")
}
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}
tasks.register<Copy>("copyToLib") {
from(project.configurations.runtime)
into(File(buildDir, "libs"))
}
tasks.register<ShadowJar>("standalone") {
archiveFileName.set("{{name}}-openapi-generator-standalone.jar")
archiveClassifier.set("all")
from(sourceSets["main"].output)
configurations.add(project.configurations["runtimeClasspath"])
configurations.add(project.configurations["runtime"])
mergeServiceFiles()
manifest.attributes(mapOf("Main-Class" to "org.openapitools.codegen.OpenAPIGenerator"))
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.wrapper {
this.distributionType = Wrapper.DistributionType.BIN
}
tasks.named("shadowJar") { dependsOn("copyToLib") }

View File

@ -0,0 +1,183 @@
@file:JvmName("{{generatorClass}}")
package {{generatorPackage}}
import org.openapitools.codegen.*
import java.util.*
import java.io.File
open class {{generatorClass}}() : DefaultCodegen(), CodegenConfig {
// source folder where files are written
private var sourceFolder = "src"
private var apiVersion = "1.0.0"
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
override fun getTag(): CodegenType {
return CodegenType.{{generatorType}}
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
override fun getName(): String {
return "{{name}}"
}
/**
* Provides an opportunity to inspect and modify operation data before the code is generated.
*/
@Suppress("UNCHECKED_CAST")
override fun postProcessOperationsWithModels(objs: Map<String, Any>, allModels: List<Any>?): Map<String, Any> {
val results = super.postProcessOperationsWithModels(objs, allModels)
val ops = results["operations"] as Map<String, Any>
val opList = ops["operation"] as ArrayList<CodegenOperation>
// iterate over the operation and perhaps modify something
for (co: CodegenOperation in opList) {
// example:
// co.httpMethod = co.httpMethod.toLowerCase();
}
return results
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
override fun getHelp(): String {
return "Generates a {{name}} client library."
}
init {
// set the output folder here
outputFolder = "generated-code/{{name}}"
/**
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles["model.mustache"] = ".sample" // the extension for each file to write
/**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles["api.mustache"] = ".sample" // the extension for each file to write
/**
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "{{name}}"
/**
* Api Package. Optional, if needed, this can be used in templates
*/
apiPackage = "org.openapitools.api"
/**
* Model Package. Optional, if needed, this can be used in templates
*/
modelPackage = "org.openapitools.model"
/**
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = HashSet(
listOf("sample1", "sample2")
)
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties["apiVersion"] = apiVersion
/**
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(
SupportingFile(
"myFile.mustache", // the input template or file
"", // the destination folder, relative `outputFolder`
"myFile.sample"
) // the output file
)
/**
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = HashSet(
listOf("Type1", "Type2")
)
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
override fun escapeReservedWord(name: String?): String {
// add an underscore to the name if it exists.
return if (name == null) "" else "_$name"
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
override fun modelFileFolder(): String {
return """$outputFolder/$sourceFolder/${modelPackage().replace('.', File.separatorChar)}"""
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
override fun apiFileFolder(): String {
return """$outputFolder/$sourceFolder/${apiPackage().replace('.', File.separatorChar)}"""
}
/**
* override with any special text escaping logic to handle unsafe
* characters so as to avoid code injection
*
* @param input String to be cleaned up
* @return string with unsafe characters removed or escaped
*/
override fun escapeUnsafeCharacters(input: String): String {
//TODO: check that this logic is safe to escape unsafe characters to avoid code injection
return input
}
/**
* Escape single and/or double quote to avoid code injection
*
* @param input String to be cleaned up
* @return string with quotation mark removed or escaped
*/
override fun escapeQuotationMark(input: String): String {
//TODO: check that this logic is safe to escape quotation mark to avoid code injection
return with(input) { replace("\"", "\\\"") }
}
}

View File

@ -0,0 +1,26 @@
package {{generatorPackage}}
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.openapitools.codegen.ClientOptInput
import org.openapitools.codegen.DefaultGenerator
import org.openapitools.codegen.config.CodegenConfigurator
internal class {{generatorClass}}Test {
// use this test to launch you code generator in the debugger.
// this allows you to easily set break points in MyclientcodegenGenerator.
@Test
fun launchCodeGenerator() {
// to understand how the 'openapi-generator-cli' module is using 'CodegenConfigurator', have a look at the 'Generate' class:
// https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java
val configurator: CodegenConfigurator = CodegenConfigurator()
.setGeneratorName("{{name}}")
.setInputSpec("https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml") // or from the server
.setOutputDir("out/{{name}}")
val clientOptInput: ClientOptInput = configurator.toClientOptInput()
val generator = DefaultGenerator()
generator.opts(clientOptInput).generate()
}
}

View File

@ -0,0 +1 @@
kotlin.code.style=official

View File

@ -0,0 +1 @@
rootProject.name = '{{kebabName}}-openapi-generator'

23
samples/meta-codegen-kotlin/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# Created by https://www.gitignore.io/api/gradle
# Edit at https://www.gitignore.io/?templates=gradle
### Gradle ###
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
#!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Gradle Patch ###
**/build/
# End of https://www.gitignore.io/api/gradle

View File

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

172
samples/meta-codegen-kotlin/gradlew vendored Executable file
View File

@ -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=""
# 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" "$@"

84
samples/meta-codegen-kotlin/gradlew.bat vendored Normal file
View File

@ -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=
@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

View File

@ -0,0 +1,60 @@
# my-client-codegen-openapi-generator
## Requirements
* Gradle 5.x
* Java 8+
## Getting Started
* Initialize the gradle wrapper:
```bash
gradle wrapper --gradle-version 5.6.2
```
* Modify the codegen class and associated templates
* Compile with `./gradlew standalone`
* Verify:
```bash
java -jar build/libs/my-client-codegen-openapi-generator-standalone.jar config-help -g myClientCodegen
```
## Building
### Standalone
As seen in "Getting Started", the generator may be built as a standalone customized version of OpenAPI Generator's CLI. This may be the simplest option for developers who are unfamiliar with working in the JVM. Please be aware of any licensing concerns before distributing this "uber-jar".
To build as a standalone, run:
```bash
./gradlew standalone
```
To list generators via OpenAPI Generator CLI:
```bash
java -jar build/libs/my-client-codegen-openapi-generator-standalone.jar list --include all
```
### ShadowJar
This generator supports building as a lightweight "fat-jar". This option includes Kotlin or any other `implementation` dependencies you'll add. This will simplify publishing if your generator has many dependencies.
To build as a shadowJar, run:
```bash
./gradlew shadowJar
```
To list generators via OpenAPI Generator CLI, you must refer to the CLI jar explicitly. We add a custom copy task which includes the CLI jar in the build output directory:
```bash
java -cp build/libs/openapi-generator-cli-4.1.3.jar:build/libs/my-client-codegen-openapi-generator-1.0-SNAPSHOT-all.jar org.openapitools.codegen.OpenAPIGenerator list
```
Notice that this command _must_ pass classpath via `-cp` and include OpenAPI Generator CLI as well as the artifact built from this project. Also notice that the manifest class must be passed explicitly as `org.openapitools.codegen.OpenAPIGenerator`.
## See Also
* [Customization docs](https://openapi-generator.tech/docs/customization)
* [Templating docs](https://openapi-generator.tech/docs/templating)

View File

@ -0,0 +1,62 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.3.41"
id("com.github.johnrengelman.shadow") version("5.0.0")
}
group = "org.openapitools"
version = "1.0-SNAPSHOT"
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
val openapiGeneratorVersion = "4.1.3"
implementation(kotlin("stdlib-jdk8"))
implementation("org.openapitools:openapi-generator:$openapiGeneratorVersion")
runtime("org.openapitools:openapi-generator-cli:$openapiGeneratorVersion")
testImplementation("org.junit.jupiter:junit-jupiter:5.5.2")
}
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}
tasks.register<Copy>("copyToLib") {
from(project.configurations.runtime)
into(File(buildDir, "libs"))
}
tasks.register<ShadowJar>("standalone") {
archiveFileName.set("myClientCodegen-openapi-generator-standalone.jar")
archiveClassifier.set("all")
from(sourceSets["main"].output)
configurations.add(project.configurations["runtimeClasspath"])
configurations.add(project.configurations["runtime"])
mergeServiceFiles()
manifest.attributes(mapOf("Main-Class" to "org.openapitools.codegen.OpenAPIGenerator"))
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.wrapper {
this.distributionType = Wrapper.DistributionType.BIN
}
tasks.named("shadowJar") { dependsOn("copyToLib") }

View File

@ -0,0 +1 @@
kotlin.code.style=official

View File

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

172
samples/meta-codegen-kotlin/lib/gradlew vendored Executable file
View File

@ -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=""
# 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" "$@"

View File

@ -0,0 +1 @@
rootProject.name = 'my-client-codegen-openapi-generator'

View File

@ -0,0 +1,183 @@
@file:JvmName("MyclientcodegenGenerator")
package com.my.company.codegen
import org.openapitools.codegen.*
import java.util.*
import java.io.File
open class MyclientcodegenGenerator() : DefaultCodegen(), CodegenConfig {
// source folder where files are written
private var sourceFolder = "src"
private var apiVersion = "1.0.0"
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
override fun getTag(): CodegenType {
return CodegenType.DOCUMENTATION
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
override fun getName(): String {
return "myClientCodegen"
}
/**
* Provides an opportunity to inspect and modify operation data before the code is generated.
*/
@Suppress("UNCHECKED_CAST")
override fun postProcessOperationsWithModels(objs: Map<String, Any>, allModels: List<Any>?): Map<String, Any> {
val results = super.postProcessOperationsWithModels(objs, allModels)
val ops = results["operations"] as Map<String, Any>
val opList = ops["operation"] as ArrayList<CodegenOperation>
// iterate over the operation and perhaps modify something
for (co: CodegenOperation in opList) {
// example:
// co.httpMethod = co.httpMethod.toLowerCase();
}
return results
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
override fun getHelp(): String {
return "Generates a myClientCodegen client library."
}
init {
// set the output folder here
outputFolder = "generated-code/myClientCodegen"
/**
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles["model.mustache"] = ".sample" // the extension for each file to write
/**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles["api.mustache"] = ".sample" // the extension for each file to write
/**
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "myClientCodegen"
/**
* Api Package. Optional, if needed, this can be used in templates
*/
apiPackage = "org.openapitools.api"
/**
* Model Package. Optional, if needed, this can be used in templates
*/
modelPackage = "org.openapitools.model"
/**
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = HashSet(
listOf("sample1", "sample2")
)
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties["apiVersion"] = apiVersion
/**
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(
SupportingFile(
"myFile.mustache", // the input template or file
"", // the destination folder, relative `outputFolder`
"myFile.sample"
) // the output file
)
/**
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = HashSet(
listOf("Type1", "Type2")
)
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
override fun escapeReservedWord(name: String?): String {
// add an underscore to the name if it exists.
return if (name == null) "" else "_$name"
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
override fun modelFileFolder(): String {
return """$outputFolder/$sourceFolder/${modelPackage().replace('.', File.separatorChar)}"""
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
override fun apiFileFolder(): String {
return """$outputFolder/$sourceFolder/${apiPackage().replace('.', File.separatorChar)}"""
}
/**
* override with any special text escaping logic to handle unsafe
* characters so as to avoid code injection
*
* @param input String to be cleaned up
* @return string with unsafe characters removed or escaped
*/
override fun escapeUnsafeCharacters(input: String): String {
//TODO: check that this logic is safe to escape unsafe characters to avoid code injection
return input
}
/**
* Escape single and/or double quote to avoid code injection
*
* @param input String to be cleaned up
* @return string with quotation mark removed or escaped
*/
override fun escapeQuotationMark(input: String): String {
//TODO: check that this logic is safe to escape quotation mark to avoid code injection
return with(input) { replace("\"", "\\\"") }
}
}

View File

@ -0,0 +1 @@
com.my.company.codegen.MyclientcodegenGenerator

View File

@ -0,0 +1,28 @@
# This is a sample api mustache template. It is representing a ficticous
# language and won't be usable or compile to anything without lots of changes.
# Use it as an example. You can access the variables in the generator object
# like such:
# use the package from the `apiPackage` variable
package: {{package}}
# operations block
{{#operations}}
classname: {{classname}}
# loop over each operation in the API:
{{#operation}}
# each operation has an `operationId`:
operationId: {{operationId}}
# and parameters:
{{#allParams}}
{{paramName}}: {{dataType}}
{{/allParams}}
{{/operation}}
# end of operations block
{{/operations}}

View File

@ -0,0 +1 @@
# This is a sample model mustache template.

View File

@ -0,0 +1 @@
# This is a sample supporting file mustache template.

View File

@ -0,0 +1,26 @@
package com.my.company.codegen
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.openapitools.codegen.ClientOptInput
import org.openapitools.codegen.DefaultGenerator
import org.openapitools.codegen.config.CodegenConfigurator
internal class MyclientcodegenGeneratorTest {
// use this test to launch you code generator in the debugger.
// this allows you to easily set break points in MyclientcodegenGenerator.
@Test
fun launchCodeGenerator() {
// to understand how the 'openapi-generator-cli' module is using 'CodegenConfigurator', have a look at the 'Generate' class:
// https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java
val configurator: CodegenConfigurator = CodegenConfigurator()
.setGeneratorName("myClientCodegen")
.setInputSpec("https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml") // or from the server
.setOutputDir("out/myClientCodegen")
val clientOptInput: ClientOptInput = configurator.toClientOptInput()
val generator = DefaultGenerator()
generator.opts(clientOptInput).generate()
}
}

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1 @@
unset

View File

@ -0,0 +1 @@
# This is a sample supporting file mustache template.

View File

@ -0,0 +1,76 @@
# This is a sample api mustache template. It is representing a ficticous
# language and won't be usable or compile to anything without lots of changes.
# Use it as an example. You can access the variables in the generator object
# like such:
# use the package from the `apiPackage` variable
package: org.openapitools.api
# operations block
classname: PetApi
# loop over each operation in the API:
# each operation has an `operationId`:
operationId: addPet
# and parameters:
body: Pet
# each operation has an `operationId`:
operationId: deletePet
# and parameters:
petId: Long
apiKey: String
# each operation has an `operationId`:
operationId: findPetsByStatus
# and parameters:
status: List
# each operation has an `operationId`:
operationId: findPetsByTags
# and parameters:
tags: List
# each operation has an `operationId`:
operationId: getPetById
# and parameters:
petId: Long
# each operation has an `operationId`:
operationId: updatePet
# and parameters:
body: Pet
# each operation has an `operationId`:
operationId: updatePetWithForm
# and parameters:
petId: String
name: String
status: String
# each operation has an `operationId`:
operationId: uploadFile
# and parameters:
petId: Long
additionalMetadata: String
file: File
# end of operations block

View File

@ -0,0 +1,42 @@
# This is a sample api mustache template. It is representing a ficticous
# language and won't be usable or compile to anything without lots of changes.
# Use it as an example. You can access the variables in the generator object
# like such:
# use the package from the `apiPackage` variable
package: org.openapitools.api
# operations block
classname: StoreApi
# loop over each operation in the API:
# each operation has an `operationId`:
operationId: deleteOrder
# and parameters:
orderId: String
# each operation has an `operationId`:
operationId: getInventory
# and parameters:
# each operation has an `operationId`:
operationId: getOrderById
# and parameters:
orderId: String
# each operation has an `operationId`:
operationId: placeOrder
# and parameters:
body: Order
# end of operations block

View File

@ -0,0 +1,72 @@
# This is a sample api mustache template. It is representing a ficticous
# language and won't be usable or compile to anything without lots of changes.
# Use it as an example. You can access the variables in the generator object
# like such:
# use the package from the `apiPackage` variable
package: org.openapitools.api
# operations block
classname: UserApi
# loop over each operation in the API:
# each operation has an `operationId`:
operationId: createUser
# and parameters:
body: User
# each operation has an `operationId`:
operationId: createUsersWithArrayInput
# and parameters:
body: List
# each operation has an `operationId`:
operationId: createUsersWithListInput
# and parameters:
body: List
# each operation has an `operationId`:
operationId: deleteUser
# and parameters:
username: String
# each operation has an `operationId`:
operationId: getUserByName
# and parameters:
username: String
# each operation has an `operationId`:
operationId: loginUser
# and parameters:
username: String
password: String
# each operation has an `operationId`:
operationId: logoutUser
# and parameters:
# each operation has an `operationId`:
operationId: updateUser
# and parameters:
username: String
body: User
# end of operations block

View File

@ -0,0 +1 @@
# This is a sample model mustache template.

View File

@ -0,0 +1 @@
# This is a sample model mustache template.

View File

@ -0,0 +1 @@
# This is a sample model mustache template.

View File

@ -0,0 +1 @@
# This is a sample model mustache template.

View File

@ -0,0 +1 @@
# This is a sample model mustache template.