From 753553622f7b8371683601a734e6e46b8771242b Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Fri, 8 Jan 2021 16:57:51 -0700 Subject: [PATCH 01/20] adding baseline template files --- src/README-GEN.md | 85 ++++++++++++ .../twilio/oai/AbstractTwilioGoGenerator.java | 35 +++++ .../com/twilio/oai/TwilioGoGenerator.java | 65 +++++++++ .../twilio/oai/TwilioTerraformGenerator.java | 107 +++++++++++++++ .../org.openapitools.codegen.CodegenConfig | 2 + .../terraform-provider-twilio/api.mustache | 90 ++++++++++++ .../api_doc.mustache | 59 ++++++++ .../partial_header.mustache | 23 ++++ src/main/resources/twilio-go/README.mustache | 117 ++++++++++++++++ src/main/resources/twilio-go/api.mustache | 120 ++++++++++++++++ src/main/resources/twilio-go/api_doc.mustache | 59 ++++++++ src/main/resources/twilio-go/model.mustache | 43 ++++++ .../resources/twilio-go/model_doc.mustache | 12 ++ .../twilio-go/partial_header.mustache | 23 ++++ .../resources/twilio-go/response.mustache | 38 ++++++ src/pom.xml | 128 ++++++++++++++++++ .../com/twilio/oai/TwilioGoGeneratorTest.java | 36 +++++ 17 files changed, 1042 insertions(+) create mode 100644 src/README-GEN.md create mode 100644 src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java create mode 100644 src/main/java/com/twilio/oai/TwilioGoGenerator.java create mode 100644 src/main/java/com/twilio/oai/TwilioTerraformGenerator.java create mode 100644 src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig create mode 100644 src/main/resources/terraform-provider-twilio/api.mustache create mode 100644 src/main/resources/terraform-provider-twilio/api_doc.mustache create mode 100644 src/main/resources/terraform-provider-twilio/partial_header.mustache create mode 100644 src/main/resources/twilio-go/README.mustache create mode 100644 src/main/resources/twilio-go/api.mustache create mode 100644 src/main/resources/twilio-go/api_doc.mustache create mode 100644 src/main/resources/twilio-go/model.mustache create mode 100644 src/main/resources/twilio-go/model_doc.mustache create mode 100644 src/main/resources/twilio-go/partial_header.mustache create mode 100644 src/main/resources/twilio-go/response.mustache create mode 100644 src/pom.xml create mode 100644 src/test/java/com/twilio/oai/TwilioGoGeneratorTest.java diff --git a/src/README-GEN.md b/src/README-GEN.md new file mode 100644 index 000000000..8bd66d6e0 --- /dev/null +++ b/src/README-GEN.md @@ -0,0 +1,85 @@ +# OpenAPI Generator for the 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. + +## 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? +At this point, you've likely generated a client setup. It will include something along these lines: + +``` +. +|- 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/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java new file mode 100644 index 000000000..1b3a9ff89 --- /dev/null +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -0,0 +1,35 @@ +package com.twilio.oai; + +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.GoClientCodegen; + +import java.util.HashMap; +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); + } +} 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..c4ba5f32a --- /dev/null +++ b/src/main/java/com/twilio/oai/TwilioGoGenerator.java @@ -0,0 +1,65 @@ +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/java/com/twilio/oai/TwilioTerraformGenerator.java b/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java new file mode 100644 index 000000000..b94db0e40 --- /dev/null +++ b/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java @@ -0,0 +1,107 @@ +package com.twilio.oai; + +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.utils.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TwilioTerraformGenerator extends AbstractTwilioGoGenerator { + + public TwilioTerraformGenerator() { + super(); + + typeMapping.put("object", "string"); + } + + @SuppressWarnings("unchecked") + @Override + public Map postProcessOperationsWithModels(final Map objs, final List allModels) { + final Map results = super.postProcessOperationsWithModels(objs, allModels); + + final Map> resources = new HashMap<>(); + + final Map ops = (Map) results.get("operations"); + final ArrayList opList = (ArrayList) ops.get("operation"); + + // Drop list operations since they're not needed in CRUD operations. + opList.removeIf(co -> co.nickname.endsWith("List")); + + // iterate over the operation and perhaps modify something + for (final CodegenOperation co : opList) { + co.vendorExtensions.put("x-is-create-operation", co.nickname.endsWith("Create")); + co.vendorExtensions.put("x-is-read-operation", co.nickname.endsWith("Read")); + co.vendorExtensions.put("x-is-update-operation", co.nickname.endsWith("Update")); + co.vendorExtensions.put("x-is-delete-operation", co.nickname.endsWith("Delete")); + + this.addParamVendorExtensions(co.allParams); + this.addParamVendorExtensions(co.optionalParams); + + // Group operations by resource. + final String resourceName = co.path + .replaceFirst("/[^/]+", "") // Drop the version + .replaceAll("/\\{.+?}", "") // Drop every path parameter + .replace(".json", "") // Drop the JSON extension + .replace("/", ""); // Drop the path separators + + final Map resource = resources.computeIfAbsent(resourceName, k -> new HashMap<>()); + final Map resourceOperations = (Map) resource.computeIfAbsent("operations", k -> new HashMap<>()); + final ArrayList resourceOperationList = (ArrayList) resourceOperations.computeIfAbsent("operation", k -> new ArrayList<>()); + + resource.put("name", resourceName); + resourceOperationList.add(co); + + // Use the parameters for creating the resource as the resource schema. + if (co.nickname.endsWith("Create")) { + resource.put("schema", co.allParams); + } + } + + final String inputSpecPattern = ".+?_(.+?)_(.+?)\\.(.+)"; + + final String productVersion = StringUtils.camelize(getInputSpec() + .replaceAll(inputSpecPattern, "$1_$2")); + final String clientPath = getInputSpec() + .replaceAll(inputSpecPattern, "$1/$2"); + + results.put("productVersion", productVersion); + results.put("clientPath", clientPath); + results.put("resources", resources.values()); + + return results; + } + + private void addParamVendorExtensions(final List params) { + params.forEach(p -> p.vendorExtensions.put("x-name-in-snake-case", this.toSnakeCase(p.baseName))); + params.forEach(p -> p.vendorExtensions.put("x-util-name", p.isFreeFormObject ? "Object" : "String")); + } + + private String toSnakeCase(final String string) { + return string.replaceAll("([a-z\\d])([A-Z])", "$1_$2").toLowerCase(); + } + + /** + * 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 "terraform-provider-twilio"; + } + + /** + * 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 Terraform provider (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..b6619e1eb --- /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}} + "{{import}}" + {{/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}} + {{baseName}} *{{{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 "{{baseName}}" ({{#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, "{"+"{{baseName}}"+"}", {{paramName}}, -1) + {{/pathParams}} + + data := {{#hasOptionalParams}}url.Values{}{{/hasOptionalParams}}{{^hasOptionalParams}}0{{/hasOptionalParams}} + headers := {{#hasHeaderParams}}make(map[string]interface{}){{/hasHeaderParams}}{{^hasHeaderParams}}0{{/hasHeaderParams}} + + {{#hasOptionalParams}} + {{#optionalParams}} + {{^isHeaderParam}} + if params != nil && params.{{baseName}} != nil { + {{#isFreeFormObject}} + v, err := json.Marshal(params.{{baseName}}) + + if err != nil { + return nil, err + } + + data.Set("{{baseName}}", string(v)) + {{/isFreeFormObject}} + {{^isFreeFormObject}} + data.Set("{{baseName}}", {{^isString}}string({{/isString}}*params.{{baseName}}{{^isString}}){{/isString}}) + {{/isFreeFormObject}} + } + {{/isHeaderParam}} + {{/optionalParams}} + {{/hasOptionalParams}} + + {{#hasHeaderParams}} + {{#headerParams}} + if params != nil && params.{{baseName}} != nil { + headers["{{baseName}}"] = *params.{{baseName}} + } + {{/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..5ddad640c --- /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..f30047a9e --- /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:"{{baseName}}{{^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..4691e8f42 --- /dev/null +++ b/src/main/resources/twilio-go/response.mustache @@ -0,0 +1,38 @@ +{{>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/pom.xml b/src/pom.xml new file mode 100644 index 000000000..a00ffb3d1 --- /dev/null +++ b/src/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/test/java/com/twilio/oai/TwilioGoGeneratorTest.java b/src/test/java/com/twilio/oai/TwilioGoGeneratorTest.java new file mode 100644 index 000000000..c91394a0a --- /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(); + } +} \ No newline at end of file From 01eadd0b49cff87f2f3d768ca7c3492f4f93d18b Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Mon, 11 Jan 2021 14:27:30 -0700 Subject: [PATCH 02/20] Adding template files --- src/{README-GEN.md => README.md} | 0 .../twilio/oai/TwilioTerraformGenerator.java | 107 ------------------ 2 files changed, 107 deletions(-) rename src/{README-GEN.md => README.md} (100%) delete mode 100644 src/main/java/com/twilio/oai/TwilioTerraformGenerator.java diff --git a/src/README-GEN.md b/src/README.md similarity index 100% rename from src/README-GEN.md rename to src/README.md diff --git a/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java b/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java deleted file mode 100644 index b94db0e40..000000000 --- a/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.twilio.oai; - -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.utils.StringUtils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class TwilioTerraformGenerator extends AbstractTwilioGoGenerator { - - public TwilioTerraformGenerator() { - super(); - - typeMapping.put("object", "string"); - } - - @SuppressWarnings("unchecked") - @Override - public Map postProcessOperationsWithModels(final Map objs, final List allModels) { - final Map results = super.postProcessOperationsWithModels(objs, allModels); - - final Map> resources = new HashMap<>(); - - final Map ops = (Map) results.get("operations"); - final ArrayList opList = (ArrayList) ops.get("operation"); - - // Drop list operations since they're not needed in CRUD operations. - opList.removeIf(co -> co.nickname.endsWith("List")); - - // iterate over the operation and perhaps modify something - for (final CodegenOperation co : opList) { - co.vendorExtensions.put("x-is-create-operation", co.nickname.endsWith("Create")); - co.vendorExtensions.put("x-is-read-operation", co.nickname.endsWith("Read")); - co.vendorExtensions.put("x-is-update-operation", co.nickname.endsWith("Update")); - co.vendorExtensions.put("x-is-delete-operation", co.nickname.endsWith("Delete")); - - this.addParamVendorExtensions(co.allParams); - this.addParamVendorExtensions(co.optionalParams); - - // Group operations by resource. - final String resourceName = co.path - .replaceFirst("/[^/]+", "") // Drop the version - .replaceAll("/\\{.+?}", "") // Drop every path parameter - .replace(".json", "") // Drop the JSON extension - .replace("/", ""); // Drop the path separators - - final Map resource = resources.computeIfAbsent(resourceName, k -> new HashMap<>()); - final Map resourceOperations = (Map) resource.computeIfAbsent("operations", k -> new HashMap<>()); - final ArrayList resourceOperationList = (ArrayList) resourceOperations.computeIfAbsent("operation", k -> new ArrayList<>()); - - resource.put("name", resourceName); - resourceOperationList.add(co); - - // Use the parameters for creating the resource as the resource schema. - if (co.nickname.endsWith("Create")) { - resource.put("schema", co.allParams); - } - } - - final String inputSpecPattern = ".+?_(.+?)_(.+?)\\.(.+)"; - - final String productVersion = StringUtils.camelize(getInputSpec() - .replaceAll(inputSpecPattern, "$1_$2")); - final String clientPath = getInputSpec() - .replaceAll(inputSpecPattern, "$1/$2"); - - results.put("productVersion", productVersion); - results.put("clientPath", clientPath); - results.put("resources", resources.values()); - - return results; - } - - private void addParamVendorExtensions(final List params) { - params.forEach(p -> p.vendorExtensions.put("x-name-in-snake-case", this.toSnakeCase(p.baseName))); - params.forEach(p -> p.vendorExtensions.put("x-util-name", p.isFreeFormObject ? "Object" : "String")); - } - - private String toSnakeCase(final String string) { - return string.replaceAll("([a-z\\d])([A-Z])", "$1_$2").toLowerCase(); - } - - /** - * 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 "terraform-provider-twilio"; - } - - /** - * 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 Terraform provider (beta)."; - } -} From 755097e6355167c3bbfcf6152185241002658aee Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Mon, 11 Jan 2021 14:27:30 -0700 Subject: [PATCH 03/20] Adding template files --- src/{README-GEN.md => README.md} | 0 .../twilio/oai/TwilioTerraformGenerator.java | 107 ------------------ 2 files changed, 107 deletions(-) rename src/{README-GEN.md => README.md} (100%) delete mode 100644 src/main/java/com/twilio/oai/TwilioTerraformGenerator.java diff --git a/src/README-GEN.md b/src/README.md similarity index 100% rename from src/README-GEN.md rename to src/README.md diff --git a/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java b/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java deleted file mode 100644 index b94db0e40..000000000 --- a/src/main/java/com/twilio/oai/TwilioTerraformGenerator.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.twilio.oai; - -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.utils.StringUtils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class TwilioTerraformGenerator extends AbstractTwilioGoGenerator { - - public TwilioTerraformGenerator() { - super(); - - typeMapping.put("object", "string"); - } - - @SuppressWarnings("unchecked") - @Override - public Map postProcessOperationsWithModels(final Map objs, final List allModels) { - final Map results = super.postProcessOperationsWithModels(objs, allModels); - - final Map> resources = new HashMap<>(); - - final Map ops = (Map) results.get("operations"); - final ArrayList opList = (ArrayList) ops.get("operation"); - - // Drop list operations since they're not needed in CRUD operations. - opList.removeIf(co -> co.nickname.endsWith("List")); - - // iterate over the operation and perhaps modify something - for (final CodegenOperation co : opList) { - co.vendorExtensions.put("x-is-create-operation", co.nickname.endsWith("Create")); - co.vendorExtensions.put("x-is-read-operation", co.nickname.endsWith("Read")); - co.vendorExtensions.put("x-is-update-operation", co.nickname.endsWith("Update")); - co.vendorExtensions.put("x-is-delete-operation", co.nickname.endsWith("Delete")); - - this.addParamVendorExtensions(co.allParams); - this.addParamVendorExtensions(co.optionalParams); - - // Group operations by resource. - final String resourceName = co.path - .replaceFirst("/[^/]+", "") // Drop the version - .replaceAll("/\\{.+?}", "") // Drop every path parameter - .replace(".json", "") // Drop the JSON extension - .replace("/", ""); // Drop the path separators - - final Map resource = resources.computeIfAbsent(resourceName, k -> new HashMap<>()); - final Map resourceOperations = (Map) resource.computeIfAbsent("operations", k -> new HashMap<>()); - final ArrayList resourceOperationList = (ArrayList) resourceOperations.computeIfAbsent("operation", k -> new ArrayList<>()); - - resource.put("name", resourceName); - resourceOperationList.add(co); - - // Use the parameters for creating the resource as the resource schema. - if (co.nickname.endsWith("Create")) { - resource.put("schema", co.allParams); - } - } - - final String inputSpecPattern = ".+?_(.+?)_(.+?)\\.(.+)"; - - final String productVersion = StringUtils.camelize(getInputSpec() - .replaceAll(inputSpecPattern, "$1_$2")); - final String clientPath = getInputSpec() - .replaceAll(inputSpecPattern, "$1/$2"); - - results.put("productVersion", productVersion); - results.put("clientPath", clientPath); - results.put("resources", resources.values()); - - return results; - } - - private void addParamVendorExtensions(final List params) { - params.forEach(p -> p.vendorExtensions.put("x-name-in-snake-case", this.toSnakeCase(p.baseName))); - params.forEach(p -> p.vendorExtensions.put("x-util-name", p.isFreeFormObject ? "Object" : "String")); - } - - private String toSnakeCase(final String string) { - return string.replaceAll("([a-z\\d])([A-Z])", "$1_$2").toLowerCase(); - } - - /** - * 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 "terraform-provider-twilio"; - } - - /** - * 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 Terraform provider (beta)."; - } -} From 756bd07a486fc306b723b977c91c4374db208314 Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Mon, 11 Jan 2021 14:31:22 -0700 Subject: [PATCH 04/20] Updated readme --- README.md | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 85 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8251cef70..8bd66d6e0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,85 @@ -# twilio-oai-generator -Twilio OpenAPI client generator +# OpenAPI Generator for the 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. + +## 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? +At this point, you've likely generated a client setup. It will include something along these lines: + +``` +. +|- 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 From 6b7398682bf2ea972e7de46c9dfae512b64c575c Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Mon, 11 Jan 2021 14:43:55 -0700 Subject: [PATCH 05/20] Restructing --- src/pom.xml => pom.xml | 0 src/README.md | 85 ------------------------------------------ 2 files changed, 85 deletions(-) rename src/pom.xml => pom.xml (100%) delete mode 100644 src/README.md diff --git a/src/pom.xml b/pom.xml similarity index 100% rename from src/pom.xml rename to pom.xml diff --git a/src/README.md b/src/README.md deleted file mode 100644 index 8bd66d6e0..000000000 --- a/src/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# OpenAPI Generator for the 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. - -## 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? -At this point, you've likely generated a client setup. It will include something along these lines: - -``` -. -|- 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 From a329dc9e201978aa25e47b0284e42c6a9caf66d0 Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Wed, 13 Jan 2021 15:23:03 -0700 Subject: [PATCH 06/20] Create PULL_REQUEST_TEMPLATE.md --- PULL_REQUEST_TEMPLATE.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 PULL_REQUEST_TEMPLATE.md diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..cc2827866 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,31 @@ + + +# Fixes # + +A short description of what this PR does. + +### Checklist +- [x] I acknowledge that all my contributions will be made under the project's license +- [ ] I have made a material change to the repo (functionality, testing, spelling, grammar) +- [ ] I have read the [Contribution Guidelines](https://github.com/twilio/twilio-ruby/blob/main/CONTRIBUTING.md) and my PR follows them +- [ ] I have titled the PR appropriately +- [ ] I have updated my branch with the main branch +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have added the necessary documentation about the functionality in the appropriate .md file +- [ ] I have added inline documentation to the code I modified + +If you have questions, please file a [support ticket](https://twilio.com/help/contact), or create a GitHub Issue in this repository. From 08ce488c4974d5f668401bc4bf98d850bc25c184 Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Wed, 13 Jan 2021 16:08:58 -0700 Subject: [PATCH 07/20] Delete PULL_REQUEST_TEMPLATE.md --- PULL_REQUEST_TEMPLATE.md | 31 ------------------------------- 1 file changed, 31 deletions(-) delete mode 100644 PULL_REQUEST_TEMPLATE.md diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index cc2827866..000000000 --- a/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,31 +0,0 @@ - - -# Fixes # - -A short description of what this PR does. - -### Checklist -- [x] I acknowledge that all my contributions will be made under the project's license -- [ ] I have made a material change to the repo (functionality, testing, spelling, grammar) -- [ ] I have read the [Contribution Guidelines](https://github.com/twilio/twilio-ruby/blob/main/CONTRIBUTING.md) and my PR follows them -- [ ] I have titled the PR appropriately -- [ ] I have updated my branch with the main branch -- [ ] I have added tests that prove my fix is effective or that my feature works -- [ ] I have added the necessary documentation about the functionality in the appropriate .md file -- [ ] I have added inline documentation to the code I modified - -If you have questions, please file a [support ticket](https://twilio.com/help/contact), or create a GitHub Issue in this repository. From 50f3348b97a120f453b52ead40b88276f5b40268 Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Wed, 13 Jan 2021 17:28:01 -0700 Subject: [PATCH 08/20] Adding initial contribution guidelines --- CONTRIBUTING.md | 144 +++++++++++++++++++++++++++++++++++++++++++++++ generate_code.sh | 10 ++++ 2 files changed, 154 insertions(+) create mode 100644 generate_code.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8b1378917..c128fd748 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://www.twilio.com/docs/libraries/oai-generator +[issue-link]: https://github.com/twilio/twilio-oai-generator/issues/new +[github]: https://github.com/twilio/twilio-oai-generator diff --git a/generate_code.sh b/generate_code.sh new file mode 100644 index 000000000..925282a6d --- /dev/null +++ b/generate_code.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +for domain in ~/DI/apis/*.json; do + fullname="$(basename "$domain")" + filename="${fullname%.*}" + domain_name="$(cut -d'_' -f2 <<< "$filename")" + version="$(cut -d'_' -f3 <<< "$filename")" +# echo "$domain_name" + java -cp ~/packages/openapi-generator-cli.jar:target/twilio-go-openapi-generator-1.0.0.jar org.openapitools.codegen.OpenAPIGenerator generate -g twilio-go -i "$domain" -o ./twilio-go-json/"$domain_name"/"$version" +done + From 1e5b1717a16280dd37f2587731638ad85645394f Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Wed, 13 Jan 2021 17:36:33 -0700 Subject: [PATCH 09/20] Modified generate code --- generate_code.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/generate_code.sh b/generate_code.sh index 925282a6d..d2ed82714 100644 --- a/generate_code.sh +++ b/generate_code.sh @@ -1,10 +1,10 @@ #!/usr/bin/env bash -for domain in ~/DI/apis/*.json; do +for domain in ~/DI/apis/*.yaml; do fullname="$(basename "$domain")" filename="${fullname%.*}" domain_name="$(cut -d'_' -f2 <<< "$filename")" version="$(cut -d'_' -f3 <<< "$filename")" # echo "$domain_name" - java -cp ~/packages/openapi-generator-cli.jar:target/twilio-go-openapi-generator-1.0.0.jar org.openapitools.codegen.OpenAPIGenerator generate -g twilio-go -i "$domain" -o ./twilio-go-json/"$domain_name"/"$version" + java -cp ~/packages/openapi-generator-cli.jar:target/twilio-go-openapi-generator-1.0.0.jar org.openapitools.codegen.OpenAPIGenerator generate -g twilio-go -i "$domain" -o ./twilio-go/"$domain_name"/"$version" done From 58006ea3e6cba7655b563ab9877a8e74df32b465 Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Thu, 14 Jan 2021 10:03:30 -0700 Subject: [PATCH 10/20] Updated api docs template --- src/main/resources/twilio-go/api_doc.mustache | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/resources/twilio-go/api_doc.mustache b/src/main/resources/twilio-go/api_doc.mustache index 5ddad640c..06d01c98c 100644 --- a/src/main/resources/twilio-go/api_doc.mustache +++ b/src/main/resources/twilio-go/api_doc.mustache @@ -33,7 +33,6 @@ Name | Type | Description | Notes 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}} From a1d231ab26aa10c8c9ca98fa57085757f8ebf3c1 Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Thu, 14 Jan 2021 10:24:40 -0700 Subject: [PATCH 11/20] Updated template --- src/main/resources/twilio-go/api_doc.mustache | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/resources/twilio-go/api_doc.mustache b/src/main/resources/twilio-go/api_doc.mustache index 06d01c98c..b2883dd94 100644 --- a/src/main/resources/twilio-go/api_doc.mustache +++ b/src/main/resources/twilio-go/api_doc.mustache @@ -31,8 +31,7 @@ Name | Type | Description | Notes ### Optional Parameters -Optional parameters are passed through a pointer to a {{{nickname}}}Opts struct -{{#allParams}}{{#-last}} +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}} From a882151f92afc5e350a5a21bf0749b273d11dcfb Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Thu, 14 Jan 2021 11:08:53 -0700 Subject: [PATCH 12/20] Update api_doc.mustache --- src/main/resources/twilio-go/api_doc.mustache | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/resources/twilio-go/api_doc.mustache b/src/main/resources/twilio-go/api_doc.mustache index b2883dd94..2d47f5a40 100644 --- a/src/main/resources/twilio-go/api_doc.mustache +++ b/src/main/resources/twilio-go/api_doc.mustache @@ -32,6 +32,7 @@ Name | Type | Description | Notes ### 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}} From 47a997a9b0e45e99533c6f3b26359db2e8672c01 Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Thu, 14 Jan 2021 13:03:50 -0700 Subject: [PATCH 13/20] Modified template --- generate_code.sh | 10 ---------- src/main/resources/twilio-go/api_doc.mustache | 3 ++- 2 files changed, 2 insertions(+), 11 deletions(-) delete mode 100644 generate_code.sh diff --git a/generate_code.sh b/generate_code.sh deleted file mode 100644 index d2ed82714..000000000 --- a/generate_code.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -for domain in ~/DI/apis/*.yaml; do - fullname="$(basename "$domain")" - filename="${fullname%.*}" - domain_name="$(cut -d'_' -f2 <<< "$filename")" - version="$(cut -d'_' -f3 <<< "$filename")" -# echo "$domain_name" - java -cp ~/packages/openapi-generator-cli.jar:target/twilio-go-openapi-generator-1.0.0.jar org.openapitools.codegen.OpenAPIGenerator generate -g twilio-go -i "$domain" -o ./twilio-go/"$domain_name"/"$version" -done - diff --git a/src/main/resources/twilio-go/api_doc.mustache b/src/main/resources/twilio-go/api_doc.mustache index 2d47f5a40..527ad9a1f 100644 --- a/src/main/resources/twilio-go/api_doc.mustache +++ b/src/main/resources/twilio-go/api_doc.mustache @@ -31,7 +31,8 @@ Name | Type | Description | Notes ### Optional Parameters -Optional parameters are passed through a pointer to a {{{nickname}}}Opts struct{{#allParams}}{{#-last}} +Optional parameters are passed through a pointer to a {{{nickname}}}Opts struct + {{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} From 43133353d1bf9cbe022776c88f2ffbd65bdbcea5 Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Thu, 14 Jan 2021 13:19:16 -0700 Subject: [PATCH 14/20] Updated doc --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c128fd748..789d85ac2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -140,6 +140,6 @@ you are working: * All classes and methods **must be documented**. -[docs-link]: https://www.twilio.com/docs/libraries/oai-generator +[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 From ad1767a6d16ffaf2d805d39e6bf5f53048550fa3 Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Fri, 15 Jan 2021 15:45:43 -0700 Subject: [PATCH 15/20] Updated formatting --- README.md | 26 ++-- src/main/resources/twilio-go/api.mustache | 124 +++++++++--------- .../resources/twilio-go/response.mustache | 2 - .../com/twilio/oai/TwilioGoGeneratorTest.java | 6 +- 4 files changed, 76 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index 8bd66d6e0..2802c7ead 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,19 @@ -# OpenAPI Generator for the twilio-go library +# 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. + +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. + +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? -At this point, you've likely generated a client setup. It will include something along these lines: +Clone this repo into your local machine. It will include: ``` . @@ -50,6 +50,7 @@ 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. @@ -57,19 +58,14 @@ 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 +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. +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. +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: +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: diff --git a/src/main/resources/twilio-go/api.mustache b/src/main/resources/twilio-go/api.mustache index b6619e1eb..3e57b1b25 100644 --- a/src/main/resources/twilio-go/api.mustache +++ b/src/main/resources/twilio-go/api.mustache @@ -5,30 +5,30 @@ package {{packageName}} import ( "encoding/json" "fmt" - twilio "github.com/twilio/twilio-go/client" - "net/url" - {{#imports}} - "{{import}}" - {{/imports}} + twilio "github.com/twilio/twilio-go/client" + "net/url" + {{#imports}} + "{{import}}" + {{/imports}} ) type {{classname}}Service struct { - baseURL string - client *twilio.Client + 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), - } + 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}} - {{baseName}} *{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{baseName}} *{{{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}} @@ -54,67 +54,67 @@ type {{{nickname}}}Params struct { {{/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, "{"+"{{baseName}}"+"}", {{paramName}}, -1) - {{/pathParams}} + path := "{{{path}}}" + {{#pathParams}} + path = strings.Replace(path, "{"+"{{baseName}}"+"}", {{paramName}}, -1) + {{/pathParams}} - data := {{#hasOptionalParams}}url.Values{}{{/hasOptionalParams}}{{^hasOptionalParams}}0{{/hasOptionalParams}} - headers := {{#hasHeaderParams}}make(map[string]interface{}){{/hasHeaderParams}}{{^hasHeaderParams}}0{{/hasHeaderParams}} + data := {{#hasOptionalParams}}url.Values{}{{/hasOptionalParams}}{{^hasOptionalParams}}0{{/hasOptionalParams}} + headers := {{#hasHeaderParams}}make(map[string]interface{}){{/hasHeaderParams}}{{^hasHeaderParams}}0{{/hasHeaderParams}} - {{#hasOptionalParams}} - {{#optionalParams}} - {{^isHeaderParam}} - if params != nil && params.{{baseName}} != nil { - {{#isFreeFormObject}} - v, err := json.Marshal(params.{{baseName}}) + {{#hasOptionalParams}} + {{#optionalParams}} + {{^isHeaderParam}} + if params != nil && params.{{baseName}} != nil { + {{#isFreeFormObject}} + v, err := json.Marshal(params.{{baseName}}) - if err != nil { - return nil, err - } + if err != nil { + return nil, err + } - data.Set("{{baseName}}", string(v)) - {{/isFreeFormObject}} - {{^isFreeFormObject}} - data.Set("{{baseName}}", {{^isString}}string({{/isString}}*params.{{baseName}}{{^isString}}){{/isString}}) - {{/isFreeFormObject}} - } - {{/isHeaderParam}} - {{/optionalParams}} - {{/hasOptionalParams}} + data.Set("{{baseName}}", string(v)) + {{/isFreeFormObject}} + {{^isFreeFormObject}} + data.Set("{{baseName}}", {{^isString}}string({{/isString}}*params.{{baseName}}{{^isString}}){{/isString}}) + {{/isFreeFormObject}} + } + {{/isHeaderParam}} + {{/optionalParams}} + {{/hasOptionalParams}} - {{#hasHeaderParams}} - {{#headerParams}} - if params != nil && params.{{baseName}} != nil { - headers["{{baseName}}"] = *params.{{baseName}} - } - {{/headerParams}} - {{/hasHeaderParams}} + {{#hasHeaderParams}} + {{#headerParams}} + if params != nil && params.{{baseName}} != nil { + headers["{{baseName}}"] = *params.{{baseName}} + } + {{/headerParams}} + {{/hasHeaderParams}} - resp, err := c.client.{{httpMethod}}(c.baseURL+path, data, headers) - {{#returnType}} - if err != nil { - return nil, err - } + resp, err := c.client.{{httpMethod}}(c.baseURL+path, data, headers) + {{#returnType}} + if err != nil { + return nil, err + } - defer resp.Body.Close() + defer resp.Body.Close() - ps := &{{{returnType}}}{} - if err := json.NewDecoder(resp.Body).Decode(ps); err != nil { - return nil, err - } + 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 - } + return ps, err + {{/returnType}} + {{^returnType}} + if err != nil { + return err + } - defer resp.Body.Close() + defer resp.Body.Close() - return nil - {{/returnType}} + return nil + {{/returnType}} } {{/operation}} {{/operations}} diff --git a/src/main/resources/twilio-go/response.mustache b/src/main/resources/twilio-go/response.mustache index 4691e8f42..bb8478a15 100644 --- a/src/main/resources/twilio-go/response.mustache +++ b/src/main/resources/twilio-go/response.mustache @@ -25,14 +25,12 @@ type APIResponse struct { // 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 index c91394a0a..5d9b24f7e 100644 --- a/src/test/java/com/twilio/oai/TwilioGoGeneratorTest.java +++ b/src/test/java/com/twilio/oai/TwilioGoGeneratorTest.java @@ -25,12 +25,12 @@ public void launchCodeGenerator() { // 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 +// .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(); } -} \ No newline at end of file +} From 9c5363ece6c463a4b3861aaab1a80d7444c095a7 Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Thu, 21 Jan 2021 15:01:16 -0700 Subject: [PATCH 16/20] Fixing build issues with go code --- .../twilio/oai/AbstractTwilioGoGenerator.java | 51 +++++++++++++++++++ .../com/twilio/oai/TwilioGoGenerator.java | 1 + src/main/resources/twilio-go/api.mustache | 12 +++-- src/main/resources/twilio-go/model.mustache | 2 +- 4 files changed, 60 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java index 1b3a9ff89..a5a35b25c 100644 --- a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -2,6 +2,9 @@ import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.languages.GoClientCodegen; +import org.openapitools.codegen.CodegenProperty; +import static org.openapitools.codegen.utils.StringUtils.camelize; +import io.swagger.v3.oas.models.media.Schema; import java.util.HashMap; import java.util.Map; @@ -32,4 +35,52 @@ public Map createMapping(final String key, final String value) { 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 CodegenProperty fromProperty(String name, Schema p) { + CodegenProperty prop = super.fromProperty(name, p); + prop = super.fromProperty(name, p); + String cc = camelize(prop.name, true); + if (isReservedWord(cc)) { + cc = escapeReservedWord(cc); + } + prop.nameInCamelCase = cc; + prop.baseName = prop.baseName.replaceAll("[-+.^:,]",""); + System.out.println("basename="+prop.baseName); + return prop; + } + +// @Override +// public String toParamName(String name) { +// // params should be lowerCamelCase. E.g. "person Person", instead of +// // "Person Person". +// // +// name = camelize(toVarName(name), true); +// +// // REVISIT: Actually, for idiomatic go, the param name should +// // really should just be a letter, e.g. "p Person"), but we'll get +// // around to that some other time... Maybe. +// if (isReservedWord(name)) { +// name = name + "_"; +// } +// +// name = name.replaceAll("[-+.^:,]",""); +// name = name.replace("<","lesserThan"); +// name = name.replace(">","greaterThan"); +// +// return name; +// } } diff --git a/src/main/java/com/twilio/oai/TwilioGoGenerator.java b/src/main/java/com/twilio/oai/TwilioGoGenerator.java index c4ba5f32a..646d8cea3 100644 --- a/src/main/java/com/twilio/oai/TwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/TwilioGoGenerator.java @@ -62,4 +62,5 @@ public String getName() { public String getHelp() { return "Generates a Go client library (beta)."; } + } diff --git a/src/main/resources/twilio-go/api.mustache b/src/main/resources/twilio-go/api.mustache index 3e57b1b25..0fec037db 100644 --- a/src/main/resources/twilio-go/api.mustache +++ b/src/main/resources/twilio-go/api.mustache @@ -7,8 +7,8 @@ import ( "fmt" twilio "github.com/twilio/twilio-go/client" "net/url" + "strings" {{#imports}} - "{{import}}" {{/imports}} ) @@ -28,7 +28,9 @@ func New{{classname}}Service(client *twilio.Client) *{{classname}}Service { // {{{nickname}}}Params Optional parameters for the method '{{{nickname}}}' type {{{nickname}}}Params struct { {{#optionalParams}} - {{baseName}} *{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{^isHeaderParam}} + {{baseName}} *{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}}{{/vendorExtensions.x-go-custom-tag}}` + {{/isHeaderParam}} {{/optionalParams}} } {{/hasOptionalParams}} @@ -59,7 +61,7 @@ func (c *{{{classname}}}Service) {{{nickname}}}({{#allParams}}{{#required}}{{par path = strings.Replace(path, "{"+"{{baseName}}"+"}", {{paramName}}, -1) {{/pathParams}} - data := {{#hasOptionalParams}}url.Values{}{{/hasOptionalParams}}{{^hasOptionalParams}}0{{/hasOptionalParams}} + data := {{#hasOptionalParams}}url.Values{}{{/hasOptionalParams}}{{^hasOptionalParams}}""{{/hasOptionalParams}} headers := {{#hasHeaderParams}}make(map[string]interface{}){{/hasHeaderParams}}{{^hasHeaderParams}}0{{/hasHeaderParams}} {{#hasOptionalParams}} @@ -73,10 +75,10 @@ func (c *{{{classname}}}Service) {{{nickname}}}({{#allParams}}{{#required}}{{par return nil, err } - data.Set("{{baseName}}", string(v)) + data.Set("{{baseName}}", fmt.Sprint(v)) {{/isFreeFormObject}} {{^isFreeFormObject}} - data.Set("{{baseName}}", {{^isString}}string({{/isString}}*params.{{baseName}}{{^isString}}){{/isString}}) + data.Set("{{baseName}}", {{^isString}}fmt.Sprint({{/isString}}*params.{{baseName}}{{^isString}}){{/isString}}) {{/isFreeFormObject}} } {{/isHeaderParam}} diff --git a/src/main/resources/twilio-go/model.mustache b/src/main/resources/twilio-go/model.mustache index f30047a9e..b6b47c38d 100644 --- a/src/main/resources/twilio-go/model.mustache +++ b/src/main/resources/twilio-go/model.mustache @@ -35,7 +35,7 @@ type {{classname}} struct { {{#description}} // {{{description}}} {{/description}} - {{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{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}} From 857373a7e5fdf44a16da4ad391efb80f82e10131 Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Fri, 22 Jan 2021 13:37:01 -0700 Subject: [PATCH 17/20] Fixing issues with generated code --- .../twilio/oai/AbstractTwilioGoGenerator.java | 154 ++++++++++-------- src/main/resources/twilio-go/api.mustache | 20 +-- 2 files changed, 91 insertions(+), 83 deletions(-) diff --git a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java index a5a35b25c..ee89b64d8 100644 --- a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -3,84 +3,94 @@ 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 CodegenProperty fromProperty(String name, Schema p) { - CodegenProperty prop = super.fromProperty(name, p); - prop = super.fromProperty(name, p); - String cc = camelize(prop.name, true); - if (isReservedWord(cc)) { - cc = escapeReservedWord(cc); - } - prop.nameInCamelCase = cc; - prop.baseName = prop.baseName.replaceAll("[-+.^:,]",""); - System.out.println("basename="+prop.baseName); - return prop; - } - -// @Override -// public String toParamName(String name) { -// // params should be lowerCamelCase. E.g. "person Person", instead of -// // "Person Person". -// // -// name = camelize(toVarName(name), true); -// -// // REVISIT: Actually, for idiomatic go, the param name should -// // really should just be a letter, e.g. "p Person"), but we'll get -// // around to that some other time... Maybe. -// if (isReservedWord(name)) { -// name = name + "_"; -// } -// -// name = name.replaceAll("[-+.^:,]",""); -// name = name.replace("<","lesserThan"); -// name = name.replace(">","greaterThan"); -// -// return name; -// } + 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) { +// System.out.println("before sanitization="+name); + name = name.replaceAll("[-+.^:,]",""); + name = name.replace("<","lesserThan"); + name = name.replace(">","greaterThan"); + name = super.toVarName(name); + return name; + } + + + @Override + public CodegenProperty fromProperty(String name, Schema p) { + name = toVarName(name); + CodegenProperty prop = super.fromProperty(name, p); + prop.baseName = toVarName(prop.baseName); + return prop; + } + + @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.baseName = toVarName(p.baseName); + p.paramName = toVarName(p.paramName); + } + } + + return objs; + } + } diff --git a/src/main/resources/twilio-go/api.mustache b/src/main/resources/twilio-go/api.mustache index 0fec037db..ca4393e31 100644 --- a/src/main/resources/twilio-go/api.mustache +++ b/src/main/resources/twilio-go/api.mustache @@ -7,7 +7,6 @@ import ( "fmt" twilio "github.com/twilio/twilio-go/client" "net/url" - "strings" {{#imports}} {{/imports}} ) @@ -28,9 +27,7 @@ func New{{classname}}Service(client *twilio.Client) *{{classname}}Service { // {{{nickname}}}Params Optional parameters for the method '{{{nickname}}}' type {{{nickname}}}Params struct { {{#optionalParams}} - {{^isHeaderParam}} - {{baseName}} *{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}}{{/vendorExtensions.x-go-custom-tag}}` - {{/isHeaderParam}} + {{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}} @@ -58,18 +55,19 @@ type {{{nickname}}}Params struct { 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, "{"+"{{baseName}}"+"}", {{paramName}}, -1) + path = strings.Replace(path, "{"+"{{baseName}}"+"}", {{^isString}}fmt.Sprint({{/isString}}{{paramName}}{{^isString}}){{/isString}}, -1) {{/pathParams}} - data := {{#hasOptionalParams}}url.Values{}{{/hasOptionalParams}}{{^hasOptionalParams}}""{{/hasOptionalParams}} + + data := url.Values{} headers := {{#hasHeaderParams}}make(map[string]interface{}){{/hasHeaderParams}}{{^hasHeaderParams}}0{{/hasHeaderParams}} {{#hasOptionalParams}} {{#optionalParams}} {{^isHeaderParam}} - if params != nil && params.{{baseName}} != nil { + if params != nil && params.{{paramName}} != nil { {{#isFreeFormObject}} - v, err := json.Marshal(params.{{baseName}}) + v, err := json.Marshal(params.{{paramName}}) if err != nil { return nil, err @@ -78,7 +76,7 @@ func (c *{{{classname}}}Service) {{{nickname}}}({{#allParams}}{{#required}}{{par data.Set("{{baseName}}", fmt.Sprint(v)) {{/isFreeFormObject}} {{^isFreeFormObject}} - data.Set("{{baseName}}", {{^isString}}fmt.Sprint({{/isString}}*params.{{baseName}}{{^isString}}){{/isString}}) + data.Set("{{paramName}}", {{^isListContainer}}{{^isString}}fmt.Sprint({{/isString}}*params.{{paramName}}{{^isString}}){{/isString}}){{/isListContainer}} {{#isListContainer}}strings.Join(*params.{{paramName}}, ",")){{/isListContainer}} {{/isFreeFormObject}} } {{/isHeaderParam}} @@ -87,8 +85,8 @@ func (c *{{{classname}}}Service) {{{nickname}}}({{#allParams}}{{#required}}{{par {{#hasHeaderParams}} {{#headerParams}} - if params != nil && params.{{baseName}} != nil { - headers["{{baseName}}"] = *params.{{baseName}} + if params != nil && params.{{paramName}} != nil { + headers["{{paramName}}"] = *params.{{paramName}} } {{/headerParams}} {{/hasHeaderParams}} From 066c320e262a468cc2770f0da618a5ebc31f8826 Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Fri, 22 Jan 2021 17:42:01 -0700 Subject: [PATCH 18/20] Cleanup --- src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java index ee89b64d8..0b6f0e824 100644 --- a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -54,7 +54,6 @@ public void updateCodegenPropertyEnum(CodegenProperty var) { @Override public String toVarName(String name) { -// System.out.println("before sanitization="+name); name = name.replaceAll("[-+.^:,]",""); name = name.replace("<","lesserThan"); name = name.replace(">","greaterThan"); From 8aaedfb81b693c04096639951710da2270c3c92a Mon Sep 17 00:00:00 2001 From: shwetharadhakrishna Date: Sat, 23 Jan 2021 22:38:42 -0700 Subject: [PATCH 19/20] Cleanups and replacing basenames with paramnames --- .../java/com/twilio/oai/AbstractTwilioGoGenerator.java | 10 ---------- src/main/resources/twilio-go/api.mustache | 6 +++--- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java index 0b6f0e824..e88782e7d 100644 --- a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -61,15 +61,6 @@ public String toVarName(String name) { return name; } - - @Override - public CodegenProperty fromProperty(String name, Schema p) { - name = toVarName(name); - CodegenProperty prop = super.fromProperty(name, p); - prop.baseName = toVarName(prop.baseName); - return prop; - } - @Override public String toParamName(String name) { name = toVarName(name); @@ -84,7 +75,6 @@ public Map postProcessOperationsWithModels(Map o List operationList = (List) operations.get("operation"); for (CodegenOperation op : operationList) { for (CodegenParameter p : op.allParams) { - p.baseName = toVarName(p.baseName); p.paramName = toVarName(p.paramName); } } diff --git a/src/main/resources/twilio-go/api.mustache b/src/main/resources/twilio-go/api.mustache index ca4393e31..4ffc79ceb 100644 --- a/src/main/resources/twilio-go/api.mustache +++ b/src/main/resources/twilio-go/api.mustache @@ -45,7 +45,7 @@ type {{{nickname}}}Params struct { {{#hasOptionalParams}} * @param optional nil or *{{{nickname}}}Opts - Optional Parameters: {{#optionalParams}} - * @param "{{baseName}}" ({{#isNullable}}*{{/isNullable}}{{{dataType}}}) - {{#description}}{{{.}}}{{/description}} + * @param "{{paramName}}" ({{#isNullable}}*{{/isNullable}}{{{dataType}}}) - {{#description}}{{{.}}}{{/description}} {{/optionalParams}} {{/hasOptionalParams}} {{#returnType}} @@ -55,7 +55,7 @@ type {{{nickname}}}Params struct { 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, "{"+"{{baseName}}"+"}", {{^isString}}fmt.Sprint({{/isString}}{{paramName}}{{^isString}}){{/isString}}, -1) + path = strings.Replace(path, "{"+"{{paramName}}"+"}", {{^isString}}fmt.Sprint({{/isString}}{{paramName}}{{^isString}}){{/isString}}, -1) {{/pathParams}} @@ -73,7 +73,7 @@ func (c *{{{classname}}}Service) {{{nickname}}}({{#allParams}}{{#required}}{{par return nil, err } - data.Set("{{baseName}}", fmt.Sprint(v)) + 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}} From 754dfd024b358e093f8b3d6e1e6ff2f03e7e038b Mon Sep 17 00:00:00 2001 From: Shwetha Radhakrishna Date: Sat, 23 Jan 2021 22:38:42 -0700 Subject: [PATCH 20/20] Cleanups and replacing basenames with paramnames --- .../java/com/twilio/oai/AbstractTwilioGoGenerator.java | 10 ---------- src/main/resources/twilio-go/api.mustache | 6 +++--- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java index 0b6f0e824..e88782e7d 100644 --- a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -61,15 +61,6 @@ public String toVarName(String name) { return name; } - - @Override - public CodegenProperty fromProperty(String name, Schema p) { - name = toVarName(name); - CodegenProperty prop = super.fromProperty(name, p); - prop.baseName = toVarName(prop.baseName); - return prop; - } - @Override public String toParamName(String name) { name = toVarName(name); @@ -84,7 +75,6 @@ public Map postProcessOperationsWithModels(Map o List operationList = (List) operations.get("operation"); for (CodegenOperation op : operationList) { for (CodegenParameter p : op.allParams) { - p.baseName = toVarName(p.baseName); p.paramName = toVarName(p.paramName); } } diff --git a/src/main/resources/twilio-go/api.mustache b/src/main/resources/twilio-go/api.mustache index ca4393e31..4ffc79ceb 100644 --- a/src/main/resources/twilio-go/api.mustache +++ b/src/main/resources/twilio-go/api.mustache @@ -45,7 +45,7 @@ type {{{nickname}}}Params struct { {{#hasOptionalParams}} * @param optional nil or *{{{nickname}}}Opts - Optional Parameters: {{#optionalParams}} - * @param "{{baseName}}" ({{#isNullable}}*{{/isNullable}}{{{dataType}}}) - {{#description}}{{{.}}}{{/description}} + * @param "{{paramName}}" ({{#isNullable}}*{{/isNullable}}{{{dataType}}}) - {{#description}}{{{.}}}{{/description}} {{/optionalParams}} {{/hasOptionalParams}} {{#returnType}} @@ -55,7 +55,7 @@ type {{{nickname}}}Params struct { 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, "{"+"{{baseName}}"+"}", {{^isString}}fmt.Sprint({{/isString}}{{paramName}}{{^isString}}){{/isString}}, -1) + path = strings.Replace(path, "{"+"{{paramName}}"+"}", {{^isString}}fmt.Sprint({{/isString}}{{paramName}}{{^isString}}){{/isString}}, -1) {{/pathParams}} @@ -73,7 +73,7 @@ func (c *{{{classname}}}Service) {{{nickname}}}({{#allParams}}{{#required}}{{par return nil, err } - data.Set("{{baseName}}", fmt.Sprint(v)) + 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}}