Skip to content

Commit

Permalink
feat: add Kotlin model generator (#1074)
Browse files Browse the repository at this point in the history
Co-authored-by: Jonas Lagoni <jonas-lt@live.dk>
  • Loading branch information
LouisXhaferi and jonaslagoni authored Jan 18, 2023
1 parent 9e3a823 commit fcdab58
Show file tree
Hide file tree
Showing 75 changed files with 2,457 additions and 21 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ node_modules
coverage
lib
*.DS_Store
.vscode
.idea
output
12 changes: 7 additions & 5 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,23 @@
# The default owners are automatically added as reviewers when you open a pull request unless different owners are specified in the file.

# Core Champions that does a little of everything
* @magicmatatjahu @jonaslagoni @asyncapi-bot-eve
* @magicmatatjahu @jonaslagoni @asyncapi-bot-eve

# Documentation champions
/docs

# Input Champions for AsyncAPI input
*/processors/AsyncAPIInputProcessor*.ts
*/processors/AsyncAPIInputProcessor*.ts

# Input Champions for TypeScript input
*/processors/TypeScriptInputProcessor*.ts @ron-debajyoti

# Input Champions for OpenAPI input
*/processors/OpenAPIInputProcessor*.ts
*/processors/SwaggerInputProcessor*.ts
*/processors/OpenAPIInputProcessor*.ts
*/processors/SwaggerInputProcessor*.ts

# Input Champions for JSON Schema input
*/processors/JsonSchemaInputProcessor*.ts
*/processors/JsonSchemaInputProcessor*.ts

# Language Champions for TypeScript and it's presets
*/generators/typescript @Samridhi-98
Expand All @@ -46,3 +46,5 @@
# Language Champions for Rust and its presets
*/generators/rust @leigh-johnson

# Language Champions for Kotlin and it's presets
*/generators/kotlin @LouisXhaferi
12 changes: 10 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ RUN apt-get update -yq \

# Install nodejs
RUN curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - \
&& apt-get install -yq nodejs
&& apt-get install -yq nodejs

# Install golang
RUN curl -fsSL https://golang.org/dl/go1.16.8.linux-amd64.tar.gz | tar -C /usr/local -xz
Expand All @@ -17,14 +17,22 @@ RUN apt install apt-transport-https dirmngr gnupg ca-certificates -yq \
&& apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF \
&& echo "deb https://download.mono-project.com/repo/debian stable-buster main" | tee /etc/apt/sources.list.d/mono-official-stable.list \
&& apt update -yq \
&& apt install mono-devel -yq
&& apt install mono-devel -yq

# Install rust
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y

# Install Python
RUN apt-get install -yq python

# Install Kotlin
RUN apt install -yq wget unzip \
&& cd /usr/lib \
&& wget -q https://github.com/JetBrains/kotlin/releases/download/v1.8.0/kotlin-compiler-1.8.0.zip \
&& unzip -qq kotlin-compiler-*.zip

ENV PATH $PATH:/usr/lib/kotlinc/bin

# Setup library
RUN apt-get install -yq chromium

Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,10 @@ The following table provides a short summary of available features for supported
<td><a href="./docs/usage.md#generate-python-models">Python</a></td>
<td>Class and enum generation: <em>custom indentation type and size, etc </em></td>
</tr>
<tr>
<td><a href="./docs/usage.md#generate-kotlin-models">Kotlin</a></td>
<td>Class and enum generation: <em>use of data classes where appropriate, custom indentation type and size, etc </em></td>
</tr>
</table>

## Roadmap
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,4 @@ Each language has its own limitations, corner cases, and features; thus, each la
- [Rust](./languages/Rust.md)
- [Python](./languages/Python.md)
- [TypeScript](./languages/TypeScript.md)
- [Kotlin](./languages/Kotlin.md)
52 changes: 52 additions & 0 deletions docs/languages/Kotlin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Kotlin

There are special use-cases that each language supports; this document pertains to **Kotlin models**.

Since `data classes` are used for every model that has got properties, there is no need for additional settings or
features to generate `toString()`, `equals()`, `hashCode()`, getters or setters.

Classes without properties are depicted by usual `classes`, they get no `toString()`, `equals()` or `hashCode()`
implementation. The default one should suffice here.

<!-- toc is generated with GitHub Actions do not remove toc markers -->

<!-- toc -->

- [Include KDoc for properties](#include-kdoc-for-properties)
- [Change the collection type for arrays](#change-the-collection-type-for-arrays)
- [Include Javax validation constraint annotations for properties](#include-javax-validation-constraint-annotations-for-properties)
- [Generate serializer and deserializer functionality](#generate-serializer-and-deserializer-functionality)
* [To and from JSON](#to-and-from-json)
* [To and from XML](#to-and-from-xml)
* [To and from binary](#to-and-from-binary)
<!-- tocstop -->

## Include KDoc for properties
To generate models containing `KDoc` from description and examples, use the `KOTLIN_DESCRIPTION_PRESET` option.

Check out this [example for a live demonstration](../../examples/kotlin-generate-kdoc).

## Change the collection type for arrays

Sometimes, we might want to render a different collection type, and instead of the default `Array` use as `List` type. To do so, provide the option `collectionType: 'List'`.

Check out this [example for a live demonstration](../../examples/kotlin-change-collection-type).

## Include Javax validation constraint annotations for properties

In some cases, when you generate the models from JSON Schema, you may want to include `javax.validation.constraint` annotations.

Check out this [example for a live demonstration](../../examples/kotlin-generate-javax-constraint-annotation).

## Generate serializer and deserializer functionality

The most widely used usecase for Modelina is to generate models that include serialization and deserialization functionality to convert the models into payload data. This payload data can of course be many kinds, JSON, XML, raw binary, you name it.

As you normally only need one library to do this, we developers can never get enough with creating new stuff, therefore there might be one specific library you need or want to integrate with. Therefore, there is not one specific preset that offers everything. Below is a list of all the supported serialization presets.

### To and from JSON
Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)!
### To and from XML
Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)!
### To and from binary
Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)!
4 changes: 4 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,7 @@ Rust is one of the many output languages we support. Check out this [basic examp
## Generate Python models

Python is one of the many output languages we support. Check out this [basic example for a live demonstration](../examples/generate-python-models) and the following [Python documentation for more advanced use-cases](./languages/Python.md).

## Generate Kotlin models

Kotlin is one of the many output languages we support. Check out this [basic example for a live demonstration](../examples/generate-kotlin-models) as well as [how to generate enums](../examples/generate-kotlin-enums) and the following [Kotlin documentation for more advanced use-cases](./languages/Kotlin.md).
11 changes: 10 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ We love contributions and new examples that does not already exist, you can foll
- [Java](#java)
- [C#](#c%23)
- [TypeScript](#typescript)
- [Kotlin](#kotlin)
- [Other examples](#other-examples)

<!-- tocstop -->
Expand Down Expand Up @@ -58,6 +59,7 @@ These are all the basic generator examples that shows a bare minimal example of
- [generate-java-models](./generate-java-models) - A basic example to generate Java data models.
- [generate-go-models](./generate-go-models) - A basic example to generate Go data models
- [generate-javascript-models](./generate-javascript-models) - A basic example to generate JavaScript data models
- [generate-kotlin-models](./generate-kotlin-models) - A basic example to generate Kotlin data models

## Integrations
These are examples of how you can integrate Modelina into a specific scenario:
Expand Down Expand Up @@ -107,6 +109,13 @@ These are all specific examples only relevant to the TypeScript generator:
- [typescript-use-cjs](./typescript-use-cjs) - A basic example that generate the models to use CJS module system.
- [typescript-generate-jsonbinpack](./typescript-generate-jsonbinpack) - A basic example showing how to generate models that include [jsonbinpack](https://github.com/sourcemeta/jsonbinpack) functionality.

## Kotlin
These are all specific examples only relevant to the Kotlin generator:
- [generate-kotlin-enums](./generate-kotlin-enums)
- [kotlin-generate-kdoc](./kotlin-generate-kdoc)
- [kotlin-generate-javax-constraint-annotations](./kotlin-generate-javax-constraint-annotation)
- [kotlin-change-collection-type](./kotlin-change-collection-type)

## Other examples
Miscelanious examples that do not fit into the otherwise grouping.
- [TEMPLATE](./TEMPLATE) - A basic template used to create new examples.
- [TEMPLATE](./TEMPLATE) - A basic template used to create new examples.
17 changes: 17 additions & 0 deletions examples/generate-kotlin-enums/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Kotlin Enums

A basic example of how to use Modelina and output a Kotlin enum.

## How to run this example

Run this example using:

```sh
npm i && npm run start
```

If you are on Windows, use the `start:windows` script instead:

```sh
npm i && npm run start:windows
```
12 changes: 12 additions & 0 deletions examples/generate-kotlin-enums/__snapshots__/index.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Should be able to render Kotlin Enums and should log expected output to console 1`] = `
Array [
"enum class Protocol(val value: Any) {
HTTP(\\"HTTP\\"),
NUMBER_1(1),
HTTPS(\\"HTTPS\\"),
TRUE(true);
}",
]
`;
13 changes: 13 additions & 0 deletions examples/generate-kotlin-enums/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { return; });
import {generate} from './index';

describe('Should be able to render Kotlin Enums', () => {
afterAll(() => {
jest.restoreAllMocks();
});
test('and should log expected output to console', async () => {
await generate();
expect(spy.mock.calls.length).toEqual(1);
expect(spy.mock.calls[0]).toMatchSnapshot();
});
});
20 changes: 20 additions & 0 deletions examples/generate-kotlin-enums/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { KotlinGenerator} from '../../src';

const generator = new KotlinGenerator();
const jsonSchemaDraft7 = {
$schema: 'http://json-schema.org/draft-07/schema#',
additionalProperties: false,
$id: 'protocol',
type: ['string', 'int', 'boolean'],
enum: ['HTTP', 1, 'HTTPS', true],
};

export async function generate() : Promise<void> {
const models = await generator.generate(jsonSchemaDraft7);
for (const model of models) {
console.log(model.result);
}
}
if (require.main === module) {
generate();
}
10 changes: 10 additions & 0 deletions examples/generate-kotlin-enums/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions examples/generate-kotlin-enums/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config": {
"example_name": "generate-kotlin-enums"
},
"scripts": {
"install": "cd ../.. && npm i",
"start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts",
"start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts",
"test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts",
"test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts"
}
}
17 changes: 17 additions & 0 deletions examples/generate-kotlin-models/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Kotlin Data Models

A basic example of how to use Modelina and output a Kotlin data model.

## How to run this example

Run this example using:

```sh
npm i && npm run start
```

If you are on Windows, use the `start:windows` script instead:

```sh
npm i && npm run start:windows
```
11 changes: 11 additions & 0 deletions examples/generate-kotlin-models/__snapshots__/index.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Should be able to render Kotlin Models and should log expected output to console 1`] = `
Array [
"data class Root(
val email: String,
val cache: Int,
val website: Website,
)",
]
`;
13 changes: 13 additions & 0 deletions examples/generate-kotlin-models/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { return; });
import {generate} from './index';

describe('Should be able to render Kotlin Models', () => {
afterAll(() => {
jest.restoreAllMocks();
});
test('and should log expected output to console', async () => {
await generate();
expect(spy.mock.calls.length).toEqual(3);
expect(spy.mock.calls[0]).toMatchSnapshot();
});
});
41 changes: 41 additions & 0 deletions examples/generate-kotlin-models/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { KotlinGenerator } from '../../src';

const generator = new KotlinGenerator();
const jsonSchemaDraft7 = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
additionalProperties: false,
properties: {
email: {
type: 'string',
format: 'email'
},
cache: {
type: 'integer'
},
website: {
type: 'object',
additionalProperties: false,
properties: {
domain: {
type: 'string',
format: 'url'
},
protocol: {
type: 'string',
enum: ['HTTP', 'HTTPS'],
}
}
}
}
};

export async function generate() : Promise<void> {
const models = await generator.generate(jsonSchemaDraft7);
for (const model of models) {
console.log(model.result);
}
}
if (require.main === module) {
generate();
}
10 changes: 10 additions & 0 deletions examples/generate-kotlin-models/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions examples/generate-kotlin-models/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config": {
"example_name": "generate-kotlin-models"
},
"scripts": {
"install": "cd ../.. && npm i",
"start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts",
"start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts",
"test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts",
"test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { JavaGenerator, JAVA_CONSTRAINTS_PRESET } from '../../src';

const generator = new JavaGenerator({
const generator = new JavaGenerator({
presets: [JAVA_CONSTRAINTS_PRESET]
});
const jsonSchemaDraft7 = {
Expand Down
Loading

0 comments on commit fcdab58

Please sign in to comment.