diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8b1378917..789d85ac2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1 +1,145 @@ +# Contributing to `twilio-oai-generator` +We'd love for you to contribute to our source code and to make `twilio-oai-generator` +even better than it is today! Here are the guidelines we'd like you to follow: + + - [Code of Conduct](#coc) + - [Question or Problem?](#question) + - [Issues and Bugs](#issue) + - [Feature Requests](#feature) + - [Documentation fixes](#docs) + - [Submission Guidelines](#submit) + - [Coding Rules](#rules) + + +## Code of Conduct + +Help us keep `twilio-oai-generator` open and inclusive. Please be kind to and considerate +of other developers, as we all have the same goal: make `twilio-oai-generator` as good as +it can be. + +## Got an API/Product Question or Problem? + +If you have questions about how to use `twilio-oai-generator`, please see our +[docs][docs-link], and if you don't find the answer there, please contact +[help@twilio.com](mailto:help@twilio.com) with any issues you have. + +## Found an Issue? + +If you find a bug in the source code or a mistake in the documentation, you can +help us by submitting [an issue][issue-link]. + +**Please see the [Submission Guidelines](#submit) below.** + +## Want a Feature? + +You can request a new feature by submitting an issue to our +[GitHub Repository][github]. If you would like to implement a new feature then +consider what kind of change it is: + +* **Major Changes** that you wish to contribute to the project should be + discussed first with `twilio-oai-generator` contributors in an issue or pull request so + that we can develop a proper solution and better coordinate our efforts, + prevent duplication of work, and help you to craft the change so that it is + successfully accepted into the project. +* **Small Changes** can be crafted and submitted to the + [GitHub Repository][github] as a Pull Request. + +## Want a Doc Fix? + +If you want to help improve the docs in the helper library, it's a good idea to +let others know what you're working on to minimize duplication of effort. Create +a new issue (or comment on a related existing one) to let others know what +you're working on. + +For large fixes, please build and test the documentation before submitting the +PR to be sure you haven't accidentally introduced layout or formatting issues. + + +## Submission Guidelines + +### Submitting an Issue +Before you submit your issue search the archive, maybe your question was already +answered. + +If your issue appears to be a bug, and hasn't been reported, open a new issue. +Help us to maximize the effort we can spend fixing issues and adding new +features by not reporting duplicate issues. Providing the following information +will increase the chances of your issue being dealt with quickly: + +* **Overview of the Issue** - if an error is being thrown a non-minified stack + trace helps +* **Motivation for or Use Case** - explain why this is a bug for you +* **`twilio-oai-generator` Version(s)** - is it a regression? +* **Operating System (if relevant)** - is this a problem with all systems or + only specific ones? +* **Reproduce the Error** - provide an isolated code snippet or an unambiguous + set of steps. +* **Related Issues** - has a similar issue been reported before? +* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point + to what might be causing the problem (line of code or commit) + +**If you get help, help others. Good karma rules!** + +### Submitting a Pull Request +Before you submit your pull request consider the following guidelines: + +* Search [GitHub][github] for an open or closed Pull Request that relates to + your submission. You don't want to duplicate effort. +* Make your changes in a new git branch: + + ```shell + git checkout -b my-fix-branch main + ``` + +* Create your patch, **including appropriate test cases**. +* Follow our [Coding Rules](#rules). +* Run the full `twilio-oai-generator` test suite (aliased by `make test`), and ensure + that all tests pass. +* Commit your changes using a descriptive commit message. + + ```shell + git commit -a + ``` + Note: the optional commit `-a` command line option will automatically "add" + and "rm" edited files. + +* Build your changes locally to ensure all the tests pass: + + ```shell + make test + ``` + +* Push your branch to GitHub: + + ```shell + git push origin my-fix-branch + ``` + +In GitHub, send a pull request to `twilio-oai-generator:main`. +If we suggest changes, then: + +* Make the required updates. +* Re-run the `twilio-oai-generator` test suite to ensure tests are still passing. +* Commit your changes to your branch (e.g. `my-fix-branch`). +* Push the changes to your GitHub repository (this will update your Pull Request). + +That's it! Thank you for your contribution! + +#### After your pull request is merged + +After your pull request is merged, you can safely delete your branch and pull +the changes from the main (upstream) repository. + +## Coding Rules + +To ensure consistency throughout the source code, keep these rules in mind as +you are working: + +* All features or bug fixes **must be tested** by one or more tests. +* All classes and methods **must be documented**. + + +[docs-link]: https://github.com/twilio/twilio-oai-generator/README.md +[issue-link]: https://github.com/twilio/twilio-oai-generator/issues/new +[github]: https://github.com/twilio/twilio-oai-generator diff --git a/README.md b/README.md index 8251cef70..2802c7ead 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,81 @@ -# twilio-oai-generator -Twilio OpenAPI client generator +# OpenAPI Generator for the [twilio-go](https://github.com/twilio/twilio-go/) library + +## Overview +This is a boiler-plate project to generate your own project derived from an OpenAPI specification. + +Its goal is to get you started with the basic plumbing, so you can put in your own logic. It won't work without your changes applied. Continue reading this doc to get more details on how to do that. + +## What's OpenAPI +The goal of OpenAPI is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. + +When properly described with OpenAPI, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, OpenAPI removes the guesswork in calling the service. + +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project, including additional libraries with support for other languages and more. + +## How do I use this? +Clone this repo into your local machine. It will include: + +``` +. +|- README.md // this file +|- pom.xml // build script +|-- src +|--- main +|---- java +|----- com.twilio.oai.TwilioGoGenerator.java // generator file +|---- resources +|----- twilio-go // template files +|----- META-INF +|------ services +|------- org.openapitools.codegen.CodegenConfig +``` + +You _will_ need to make changes in at least the following: + +`TwilioGoGenerator.java` + +Templates in this folder: + +`src/main/resources/twilio-go` + +Once modified, you can run this: + +``` +mvn package +``` + +In your generator project. A single jar file will be produced in `target`. You can now use that with [OpenAPI Generator](https://openapi-generator.tech): + +For mac/linux: +``` +java -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g twilio-go -i /path/to/openapi.yaml -o ./test +``` + +(Do not forget to replace the values `/path/to/openapi-generator-cli.jar`, `/path/to/your.jar` and `/path/to/openapi.yaml` in the previous command) + +For Windows users, you will need to use `;` instead of `:` in the classpath, e.g. +``` +java -cp /path/to/openapi-generator-cli.jar;/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g twilio-go -i /path/to/openapi.yaml -o ./test +``` + +Now your templates are available to the client generator, and you can write output values. + +## But how do I modify this? +The `TwilioGoGenerator.java` has comments in it--lots of comments. There is no good substitute for reading the code more, though. See how the `TwilioGoGenerator` implements `CodegenConfig`. That class has the signature of all values that can be overridden. + +You can also step through TwilioGoGenerator.java in a debugger. Just debug the JUnit test in DebugCodegenLauncher. That runs the command line tool and lets you inspect what the code is doing. + +For the templates themselves, you have a number of values available to you for generation. You can execute the `java` command from above while passing different debug flags to show the object you have available during client generation: + +``` +# The following additional debug options are available for all codegen targets: +# -DdebugOpenAPI prints the OpenAPI Specification as interpreted by the codegen +# -DdebugModels prints models passed to the template engine +# -DdebugOperations prints operations passed to the template engine +# -DdebugSupportingFiles prints additional data passed to the template engine + +java -DdebugOperations -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g twilio-go -i /path/to/openapi.yaml -o ./test +``` + +Will, for example, output the debug info for operations. +You can use this info in the `api.mustache` file. \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000..a00ffb3d1 --- /dev/null +++ b/pom.xml @@ -0,0 +1,128 @@ + + 4.0.0 + org.openapitools + twilio-go-openapi-generator + jar + twilio-go-openapi-generator + 1.0.0 + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.8 + 1.8 + + + + + + + org.openapitools + openapi-generator + ${openapi-generator-version} + provided + + + junit + junit + ${junit-version} + + + + UTF-8 + 5.0.0-beta2 + 1.0.0 + 4.8.1 + + diff --git a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java new file mode 100644 index 000000000..e88782e7d --- /dev/null +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -0,0 +1,85 @@ +package com.twilio.oai; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.GoClientCodegen; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import static org.openapitools.codegen.utils.StringUtils.camelize; +import io.swagger.v3.oas.models.media.Schema; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class AbstractTwilioGoGenerator extends GoClientCodegen { + + public AbstractTwilioGoGenerator() { + super(); + + embeddedTemplateDir = templateDir = getName(); + } + + @Override + public void processOpts() { + super.processOpts(); + + additionalProperties.put(CodegenConstants.IS_GO_SUBMODULE, true); + + supportingFiles.clear(); + } + + @Override + public Map createMapping(final String key, final String value) { + // Optional dependency not needed. + if (value.equals("github.com/antihax/optional")) { + return new HashMap<>(); + } + + return super.createMapping(key, value); + } + + @Override + public void updateCodegenPropertyEnum(CodegenProperty var) { + // make sure the inline enums have plain defaults (e.g. string, int, float) + String enumDefault = null; + if (var.isEnum && var.defaultValue != null) { + enumDefault = var.defaultValue; + } + super.updateCodegenPropertyEnum(var); + if (var.isEnum && enumDefault != null) { + var.defaultValue = enumDefault; + } + } + + @Override + public String toVarName(String name) { + name = name.replaceAll("[-+.^:,]",""); + name = name.replace("<","lesserThan"); + name = name.replace(">","greaterThan"); + name = super.toVarName(name); + return name; + } + + @Override + public String toParamName(String name) { + name = toVarName(name); + String name_sanitized = super.toParamName(name); + return name; + } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + objs = super.postProcessOperationsWithModels(objs, allModels); + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + for (CodegenParameter p : op.allParams) { + p.paramName = toVarName(p.paramName); + } + } + + return objs; + } + +} diff --git a/src/main/java/com/twilio/oai/TwilioGoGenerator.java b/src/main/java/com/twilio/oai/TwilioGoGenerator.java new file mode 100644 index 000000000..646d8cea3 --- /dev/null +++ b/src/main/java/com/twilio/oai/TwilioGoGenerator.java @@ -0,0 +1,66 @@ +package com.twilio.oai; + +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.SupportingFile; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class TwilioGoGenerator extends AbstractTwilioGoGenerator { + + @Override + public void processOpts() { + super.processOpts(); + + supportingFiles.add(new SupportingFile("README.mustache", "README.md")); + supportingFiles.add(new SupportingFile("response.mustache", "response.go")); + } + + @SuppressWarnings("unchecked") + @Override + public Map postProcessOperationsWithModels(final Map objs, final List allModels) { + final Map results = super.postProcessOperationsWithModels(objs, allModels); + + final Map ops = (Map) results.get("operations"); + final ArrayList opList = (ArrayList) ops.get("operation"); + + // iterate over the operation and perhaps modify something + for (final CodegenOperation co : opList) { + co.vendorExtensions.put("x-is-delete-operation", "DELETE".equalsIgnoreCase(co.httpMethod)); + System.out.println(co); + } + + return results; + } + + @Override + public void postProcessParameter(final CodegenParameter parameter) { + // Make sure required non-path params get into the options block. + parameter.required = parameter.isPathParam; + } + + /** + * 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 + public String getName() { + return "twilio-go"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates a Go client library (beta)."; + } + +} diff --git a/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig new file mode 100644 index 000000000..8dd1b7f3d --- /dev/null +++ b/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -0,0 +1,2 @@ +com.twilio.oai.TwilioGoGenerator +com.twilio.oai.TwilioTerraformGenerator diff --git a/src/main/resources/terraform-provider-twilio/api.mustache b/src/main/resources/terraform-provider-twilio/api.mustache new file mode 100644 index 000000000..4bc522bed --- /dev/null +++ b/src/main/resources/terraform-provider-twilio/api.mustache @@ -0,0 +1,90 @@ +{{>partial_header}} +package v2 + +import ( + "context" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/twilio/terraform-provider-twilio/client" + "github.com/twilio/terraform-provider-twilio/util" + types "github.com/twilio/twilio-go/{{clientPath}}" +) + +{{#resources}} +func Resource{{name}}() *schema.Resource { + return &schema.Resource{ + CreateContext: resource{{name}}Create, + ReadContext: resource{{name}}Read, + UpdateContext: resource{{name}}Update, + DeleteContext: resource{{name}}Delete, + Schema: map[string]*schema.Schema{ + {{#schema}} + "{{vendorExtensions.x-name-in-snake-case}}": { + Type: schema.TypeString, + {{#required}} + Required: true, + {{/required}} + {{^required}} + Optional: true, + {{/required}} + }, + {{/schema}} + }, + } +} + +{{#operations}} +{{#operation}} +func resource{{nickname}}(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + {{#hasOptionalParams}} + params := &types.{{nickname}}Params{ + {{#allParams}} + {{#required}}{{^isPathParam}}{{baseName}}: util.{{vendorExtensions.x-util-name}}(d.Get("{{vendorExtensions.x-name-in-snake-case}}").({{dataType}})),{{/isPathParam}}{{/required}} + {{/allParams}} + } + {{#allParams}}{{^required}} + if v, ok := d.GetOk("{{vendorExtensions.x-name-in-snake-case}}"); ok { + params.{{baseName}} = util.{{vendorExtensions.x-util-name}}(v.({{dataType}})) + } + {{/required}}{{/allParams}} + {{/hasOptionalParams}} + {{#vendorExtensions.x-is-create-operation}} + r, err := m.(*client.Config).Client.{{productVersion}}.{{nickname}}(params) + {{/vendorExtensions.x-is-create-operation}} + {{#vendorExtensions.x-is-delete-operation}} + err := m.(*client.Config).Client.{{productVersion}}.{{nickname}}(d.Id()) + {{/vendorExtensions.x-is-delete-operation}} + {{#vendorExtensions.x-is-read-operation}} + r, err := m.(*client.Config).Client.{{productVersion}}.{{nickname}}(d.Id(){{#hasOptionalParams}}, params{{/hasOptionalParams}}) + {{/vendorExtensions.x-is-read-operation}} + {{#vendorExtensions.x-is-update-operation}} + _, err := m.(*client.Config).Client.{{productVersion}}.{{nickname}}(d.Id(){{#hasOptionalParams}}, params{{/hasOptionalParams}}) + {{/vendorExtensions.x-is-update-operation}} + + if err != nil { + return diag.FromErr(err) + } + + {{#vendorExtensions.x-is-create-operation}} + d.SetId(r.Sid) + + return resource{{name}}Read(ctx, d, m) + {{/vendorExtensions.x-is-create-operation}} + {{#vendorExtensions.x-is-read-operation}} + {{#schema}} + d.Set("{{vendorExtensions.x-name-in-snake-case}}", r.{{baseName}}) + {{/schema}} + + return nil + {{/vendorExtensions.x-is-read-operation}} + {{#vendorExtensions.x-is-update-operation}} + return resource{{name}}Read(ctx, d, m) + {{/vendorExtensions.x-is-update-operation}} + {{#vendorExtensions.x-is-delete-operation}} + return nil + {{/vendorExtensions.x-is-delete-operation}} +} + +{{/operation}} +{{/operations}} +{{/resources}} diff --git a/src/main/resources/terraform-provider-twilio/api_doc.mustache b/src/main/resources/terraform-provider-twilio/api_doc.mustache new file mode 100644 index 000000000..5ddad640c --- /dev/null +++ b/src/main/resources/terraform-provider-twilio/api_doc.mustache @@ -0,0 +1,59 @@ +# {{invokerPackage}}\{{classname}}{{#description}} + +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{{operationId}}} + +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}(ctx, {{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Required Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-last}}{{/allParams}}{{#allParams}}{{#required}} +**{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + **optional** | ***{{{nickname}}}Opts** | optional parameters | nil if no parameters + +### Optional Parameters + +Optional parameters are passed through a pointer to a {{{nickname}}}Opts struct +{{#allParams}}{{#-last}} + +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} +{{^required}} **{{paramName}}** | {{#isFile}}**optional.Interface of {{dataType}}**{{/isFile}}{{#isPrimitiveType}}**optional.{{vendorExtensions.x-optional-data-type}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**optional.Interface of {{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{/hasOptionalParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/src/main/resources/terraform-provider-twilio/partial_header.mustache b/src/main/resources/terraform-provider-twilio/partial_header.mustache new file mode 100644 index 000000000..e23b21520 --- /dev/null +++ b/src/main/resources/terraform-provider-twilio/partial_header.mustache @@ -0,0 +1,23 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + {{#version}} + * API version: {{{version}}} + {{/version}} + {{#infoEmail}} + * Contact: {{{infoEmail}}} + {{/infoEmail}} +{{^withGoCodegenComment}} + * Generated by: OpenAPI Generator (https://openapi-generator.tech) +{{/withGoCodegenComment}} + */ +{{#withGoCodegenComment}} + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. +{{/withGoCodegenComment}} diff --git a/src/main/resources/twilio-go/README.mustache b/src/main/resources/twilio-go/README.mustache new file mode 100644 index 000000000..26d1e9904 --- /dev/null +++ b/src/main/resources/twilio-go/README.mustache @@ -0,0 +1,117 @@ +# Go API client for {{packageName}} + +{{#appDescriptionWithNewLines}} +{{{appDescriptionWithNewLines}}} +{{/appDescriptionWithNewLines}} + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation + +Install the following dependencies: + +```shell +go get github.com/stretchr/testify/assert +go get golang.org/x/net/context +``` + +Put the package under your project folder and add the following in import: + +```golang +import "./{{packageName}}" +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} Endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}} + +## {{{name}}} + +{{#isApiKey}}- **Type**: API key + +Example + +```golang +auth := context.WithValue(context.Background(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. +}) +r, err := client.Service.Operation(auth, args) +``` + +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication + +Example + +```golang +auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{ + UserName: "username", + Password: "password", +}) +r, err := client.Service.Operation(auth, args) +``` + +{{/isBasic}} +{{#isOAuth}} + +- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} + +Example + +```golang +auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING") +r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automatically refresh tokens and perform user authentication. + +```golang +import "golang.org/x/oauth2" + +/* Perform OAuth2 round trip request and obtain a token */ + +tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) +auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) +r, err := client.Service.Operation(auth, args) +``` + +{{/isOAuth}} +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/src/main/resources/twilio-go/api.mustache b/src/main/resources/twilio-go/api.mustache new file mode 100644 index 000000000..4ffc79ceb --- /dev/null +++ b/src/main/resources/twilio-go/api.mustache @@ -0,0 +1,120 @@ +{{>partial_header}} +package {{packageName}} + +{{#operations}} +import ( + "encoding/json" + "fmt" + twilio "github.com/twilio/twilio-go/client" + "net/url" + {{#imports}} + {{/imports}} +) + +type {{classname}}Service struct { + baseURL string + client *twilio.Client +} + +func New{{classname}}Service(client *twilio.Client) *{{classname}}Service { + return &{{classname}}Service { + client: client, + baseURL: fmt.Sprintf("https://studio.%s", client.BaseURL), + } +} +{{#operation}} +{{#hasOptionalParams}} +// {{{nickname}}}Params Optional parameters for the method '{{{nickname}}}' +type {{{nickname}}}Params struct { +{{#optionalParams}} + {{paramName}} *{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}}{{/vendorExtensions.x-go-custom-tag}}` +{{/optionalParams}} +} +{{/hasOptionalParams}} + +/* +{{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}} +{{#notes}} +{{notes}} +{{/notes}} +{{#allParams}} +{{#required}} + * @param {{paramName}}{{#description}} {{{.}}}{{/description}} +{{/required}} +{{/allParams}} +{{#hasOptionalParams}} + * @param optional nil or *{{{nickname}}}Opts - Optional Parameters: +{{#optionalParams}} + * @param "{{paramName}}" ({{#isNullable}}*{{/isNullable}}{{{dataType}}}) - {{#description}}{{{.}}}{{/description}} +{{/optionalParams}} +{{/hasOptionalParams}} +{{#returnType}} +@return {{{returnType}}} +{{/returnType}} +*/ +func (c *{{{classname}}}Service) {{{nickname}}}({{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}params *{{{nickname}}}Params{{/hasOptionalParams}}) ({{#returnType}}*{{{returnType}}}, {{/returnType}}error) { + path := "{{{path}}}" + {{#pathParams}} + path = strings.Replace(path, "{"+"{{paramName}}"+"}", {{^isString}}fmt.Sprint({{/isString}}{{paramName}}{{^isString}}){{/isString}}, -1) + {{/pathParams}} + + + data := url.Values{} + headers := {{#hasHeaderParams}}make(map[string]interface{}){{/hasHeaderParams}}{{^hasHeaderParams}}0{{/hasHeaderParams}} + + {{#hasOptionalParams}} + {{#optionalParams}} + {{^isHeaderParam}} + if params != nil && params.{{paramName}} != nil { + {{#isFreeFormObject}} + v, err := json.Marshal(params.{{paramName}}) + + if err != nil { + return nil, err + } + + data.Set("{{paramName}}", fmt.Sprint(v)) + {{/isFreeFormObject}} + {{^isFreeFormObject}} + data.Set("{{paramName}}", {{^isListContainer}}{{^isString}}fmt.Sprint({{/isString}}*params.{{paramName}}{{^isString}}){{/isString}}){{/isListContainer}} {{#isListContainer}}strings.Join(*params.{{paramName}}, ",")){{/isListContainer}} + {{/isFreeFormObject}} + } + {{/isHeaderParam}} + {{/optionalParams}} + {{/hasOptionalParams}} + + {{#hasHeaderParams}} + {{#headerParams}} + if params != nil && params.{{paramName}} != nil { + headers["{{paramName}}"] = *params.{{paramName}} + } + {{/headerParams}} + {{/hasHeaderParams}} + + resp, err := c.client.{{httpMethod}}(c.baseURL+path, data, headers) + {{#returnType}} + if err != nil { + return nil, err + } + + defer resp.Body.Close() + + ps := &{{{returnType}}}{} + if err := json.NewDecoder(resp.Body).Decode(ps); err != nil { + return nil, err + } + + return ps, err + {{/returnType}} + {{^returnType}} + if err != nil { + return err + } + + defer resp.Body.Close() + + return nil + {{/returnType}} +} +{{/operation}} +{{/operations}} diff --git a/src/main/resources/twilio-go/api_doc.mustache b/src/main/resources/twilio-go/api_doc.mustache new file mode 100644 index 000000000..527ad9a1f --- /dev/null +++ b/src/main/resources/twilio-go/api_doc.mustache @@ -0,0 +1,59 @@ +# {{invokerPackage}}\{{classname}}{{#description}} + +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{{operationId}}} + +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}(ctx, {{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Required Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-last}}{{/allParams}}{{#allParams}}{{#required}} +**{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + **optional** | ***{{{nickname}}}Opts** | optional parameters | nil if no parameters + +### Optional Parameters + +Optional parameters are passed through a pointer to a {{{nickname}}}Opts struct + {{#allParams}}{{#-last}} + +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} +{{^required}} **{{paramName}}** | {{#isFile}}**optional.Interface of {{dataType}}**{{/isFile}}{{#isPrimitiveType}}**optional.{{vendorExtensions.x-optional-data-type}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**optional.Interface of {{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{/hasOptionalParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/src/main/resources/twilio-go/model.mustache b/src/main/resources/twilio-go/model.mustache new file mode 100644 index 000000000..b6b47c38d --- /dev/null +++ b/src/main/resources/twilio-go/model.mustache @@ -0,0 +1,43 @@ +{{>partial_header}} +package {{packageName}} +{{#models}} +{{#imports}} +{{#-first}} +import ( +{{/-first}} + "{{import}}" +{{#-last}} +) +{{/-last}} +{{/imports}} +{{#model}} +{{#isEnum}} +// {{{classname}}} {{#description}}{{{.}}}{{/description}}{{^description}}the model '{{{classname}}}'{{/description}} +type {{{classname}}} {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}} + +// List of {{{name}}} +const ( + {{#allowableValues}} + {{#enumVars}} + {{^-first}} + {{/-first}} + {{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}} + {{/enumVars}} + {{/allowableValues}} +) +{{/isEnum}} +{{^isEnum}} +// {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}} +type {{classname}} struct { +{{#allVars}} +{{^-first}} +{{/-first}} +{{#description}} + // {{{description}}} +{{/description}} + {{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{name}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` +{{/allVars}} +} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/src/main/resources/twilio-go/model_doc.mustache b/src/main/resources/twilio-go/model_doc.mustache new file mode 100644 index 000000000..ae517d4a7 --- /dev/null +++ b/src/main/resources/twilio-go/model_doc.mustache @@ -0,0 +1,12 @@ +{{#models}}{{#model}}# {{classname}} + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#allVars}}**{{name}}** | {{#isNullable}}Pointer to {{/isNullable}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/allVars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/src/main/resources/twilio-go/partial_header.mustache b/src/main/resources/twilio-go/partial_header.mustache new file mode 100644 index 000000000..e23b21520 --- /dev/null +++ b/src/main/resources/twilio-go/partial_header.mustache @@ -0,0 +1,23 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + {{#version}} + * API version: {{{version}}} + {{/version}} + {{#infoEmail}} + * Contact: {{{infoEmail}}} + {{/infoEmail}} +{{^withGoCodegenComment}} + * Generated by: OpenAPI Generator (https://openapi-generator.tech) +{{/withGoCodegenComment}} + */ +{{#withGoCodegenComment}} + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. +{{/withGoCodegenComment}} diff --git a/src/main/resources/twilio-go/response.mustache b/src/main/resources/twilio-go/response.mustache new file mode 100644 index 000000000..bb8478a15 --- /dev/null +++ b/src/main/resources/twilio-go/response.mustache @@ -0,0 +1,36 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResponse object. +func NewAPIResponse(r *http.Response) *APIResponse { + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/src/test/java/com/twilio/oai/TwilioGoGeneratorTest.java b/src/test/java/com/twilio/oai/TwilioGoGeneratorTest.java new file mode 100644 index 000000000..5d9b24f7e --- /dev/null +++ b/src/test/java/com/twilio/oai/TwilioGoGeneratorTest.java @@ -0,0 +1,36 @@ +package com.twilio.oai; + +import org.junit.Test; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.config.CodegenConfigurator; + +/*** + * This test allows you to easily launch your code generation software under a debugger. + * Then run this test under debug mode. You will be able to step through your java code + * and then see the results in the out directory. + * + * To experiment with debugging your code generator: + * 1) Set a break point in TwilioGoGenerator.java in the postProcessOperationsWithModels() method. + * 2) To launch this test in Eclipse: right-click | Debug As | JUnit Test + * + */ +public class TwilioGoGeneratorTest { + + // use this test to launch you code generator in the debugger. + // this allows you to easily set break points in MyclientcodegenGenerator. + @Test + public void 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 + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("twilio-go") // use this codegen library +// .setInputSpec("../../../modules/openapi-generator/src/test/resources/2_0/petstore.yaml") // sample OpenAPI file + .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/twilio-go"); // output directory + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(clientOptInput).generate(); + } +}