Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[go] respect initialisms or acronyms in names #4900

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ public class DefaultCodegen implements CodegenConfig {
// acts strictly upon a spec, potentially modifying it to have consistent behavior across generators.
protected boolean strictSpecBehavior = true;

// map of exceptions for camelized names
protected Map<String, String> camelizeExeptions = new HashMap<String, String>();

// make openapi available to all methods
protected OpenAPI openAPI;

Expand Down Expand Up @@ -1790,9 +1793,9 @@ public String toSetter(String name) {
*/
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
return camelize("default_api", camelizeExeptions);
}
return camelize(name + "_" + apiNameSuffix);
return camelize(name + "_" + apiNameSuffix, camelizeExeptions);
}

/**
Expand All @@ -1803,7 +1806,7 @@ public String toApiName(String name) {
* @return capitalized model name
*/
public String toModelName(final String name) {
return camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix);
return camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix, camelizeExeptions);
}

/**
Expand Down Expand Up @@ -2151,7 +2154,7 @@ public String getterAndSetterCapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
return camelize(toVarName(name));
return camelize(toVarName(name), camelizeExeptions);
}

/**
Expand Down Expand Up @@ -2182,7 +2185,7 @@ public CodegenProperty fromProperty(String name, Schema p) {
} else {
property.openApiType = p.getType();
}
property.nameInCamelCase = camelize(property.name, false);
property.nameInCamelCase = camelize(property.name, false, camelizeExeptions);
property.nameInSnakeCase = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, property.nameInCamelCase);
property.description = escapeText(p.getDescription());
property.unescapedDescription = p.getDescription();
Expand Down Expand Up @@ -3658,7 +3661,7 @@ protected String getOrGenerateOperationId(Operation operation, String path, Stri
if (builder.toString().length() == 0) {
part = Character.toLowerCase(part.charAt(0)) + part.substring(1);
} else {
part = camelize(part);
part = camelize(part, camelizeExeptions);
}
builder.append(part);
}
Expand Down Expand Up @@ -3769,7 +3772,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera
}
co.operationId = uniqueName;
co.operationIdLowerCase = uniqueName.toLowerCase(Locale.ROOT);
co.operationIdCamelCase = camelize(uniqueName);
co.operationIdCamelCase = camelize(uniqueName, camelizeExeptions);
co.operationIdSnakeCase = underscore(uniqueName);
opList.add(co);
co.baseName = tag;
Expand Down Expand Up @@ -4326,7 +4329,7 @@ private String sanitizeValue(String value, String replaceMatch, String replaceVa
* @return Sanitized tag
*/
public String sanitizeTag(String tag) {
tag = camelize(sanitizeName(tag));
tag = camelize(sanitizeName(tag), camelizeExeptions);

// tag starts with numbers
if (tag.matches("^\\d.*")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,46 @@ public AbstractGoCodegen() {
"float32", "float64")
);

camelizeExeptions.clear();
camelizeExeptions.put("Acl", "ACL");
camelizeExeptions.put("Api", "API");
camelizeExeptions.put("Ascii", "ASCII");
camelizeExeptions.put("Cpu", "CPU");
camelizeExeptions.put("Css", "CSS");
camelizeExeptions.put("Dns", "DNS");
camelizeExeptions.put("Eof", "EOF");
camelizeExeptions.put("Guid", "GUID");
camelizeExeptions.put("Html", "HTML");
camelizeExeptions.put("Http", "HTTP");
camelizeExeptions.put("Https", "HTTPS");
camelizeExeptions.put("Id", "ID");
camelizeExeptions.put("Ip", "IP");
camelizeExeptions.put("Json", "JSON");
camelizeExeptions.put("Lhs", "LHS");
camelizeExeptions.put("Qps", "QPS");
camelizeExeptions.put("Ram", "RAM");
camelizeExeptions.put("Rhs", "RHS");
camelizeExeptions.put("Rpc", "RPS");
camelizeExeptions.put("Sla", "SLA");
camelizeExeptions.put("Smtp", "SMTP");
camelizeExeptions.put("Sql", "SQL");
camelizeExeptions.put("Ssh", "SSH");
camelizeExeptions.put("Tcp", "TCP");
camelizeExeptions.put("Tls", "TLS");
camelizeExeptions.put("Ttl", "TTL");
camelizeExeptions.put("Udp", "UDP");
camelizeExeptions.put("Ui", "UI");
camelizeExeptions.put("Uid", "UID");
camelizeExeptions.put("Uuid", "UUID");
camelizeExeptions.put("Uri", "URI");
camelizeExeptions.put("Url", "URL");
camelizeExeptions.put("Utf8", "UTF8");
camelizeExeptions.put("Vm", "VM");
camelizeExeptions.put("Xml", "XML");
camelizeExeptions.put("Xmpp", "XMPP");
camelizeExeptions.put("Xsrf", "XSRF");
camelizeExeptions.put("Xss", "XSS");

importMapping = new HashMap<String, String>();

cliOptions.clear();
Expand Down Expand Up @@ -178,8 +218,8 @@ public String toVarName(String name) {
return name;

// camelize (lower first character) the variable name
// pet_id => PetId
name = camelize(name);
// pet_id => PetID
name = camelize(name, camelizeExeptions);

// for reserved word append _
if (isReservedWord(name)) {
Expand All @@ -204,7 +244,7 @@ public String toParamName(String name) {
// params should be lowerCamelCase. E.g. "person Person", instead of
// "Person Person".
//
name = camelize(toVarName(name), true);
name = camelize(toVarName(name), true, camelizeExeptions);

// REVISIT: Actually, for idiomatic go, the param name should
// really should just be a letter, e.g. "p Person"), but we'll get
Expand All @@ -221,7 +261,7 @@ public String toParamName(String name) {
public String toModelName(String name) {
// camelize the model name
// phone_number => PhoneNumber
return camelize(toModel(name));
return camelize(toModel(name), camelizeExeptions);
}

@Override
Expand Down Expand Up @@ -338,17 +378,17 @@ public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(sanitizedOperationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to "
+ camelize("call_" + sanitizedOperationId));
+ camelize("call_" + sanitizedOperationId, camelizeExeptions));
sanitizedOperationId = "call_" + sanitizedOperationId;
}

// operationId starts with a number
if (sanitizedOperationId.matches("^\\d.*")) {
LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize("call_" + sanitizedOperationId));
LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize("call_" + sanitizedOperationId, camelizeExeptions));
sanitizedOperationId = "call_" + sanitizedOperationId;
}

return camelize(sanitizedOperationId);
return camelize(sanitizedOperationId, camelizeExeptions);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.openapitools.codegen.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
Expand Down Expand Up @@ -63,6 +64,29 @@ public static String camelize(String word) {
* @return camelized string
*/
public static String camelize(String word, boolean lowercaseFirstLetter) {
return camelize(word, lowercaseFirstLetter, new HashMap<String, String>());
}

/**
* Camelize name (parameter, property, method, etc)
*
* @param word string to be camelize
* @param camelizeExceptions map of exceptions
* @return camelized string
*/
public static String camelize(String word, Map<String, String> camelizeExceptions) {
return camelize(word, false, camelizeExceptions);
}

/**
* Camelize name (parameter, property, method, etc)
*
* @param word string to be camelize
* @param lowercaseFirstLetter lower case for first letter if set to true
* @param camelizeExceptions map of exceptions
* @return camelized string
*/
public static String camelize(String word, boolean lowercaseFirstLetter, Map<String, String> camelizeExceptions) {
// Replace all slashes with dots (package separator)
Pattern p = Pattern.compile("\\/(.?)");
Matcher m = p.matcher(word);
Expand Down Expand Up @@ -132,6 +156,11 @@ public static String camelize(String word, boolean lowercaseFirstLetter) {
// remove all underscore
word = word.replaceAll("_", "");

// exceptions
for (String key : camelizeExceptions.keySet()) {
word = word.replaceAll(key, camelizeExceptions.get(key));
}

return word;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"net/http"
)

// APIResponse stores the API response returned by the server.
type APIResponse struct {
// DefaultAPIResponse stores the API response returned by the server.
type DefaultAPIResponse struct {
*http.Response `json:"-"`
Message string `json:"message,omitempty"`
// Operation is the name of the OpenAPI operation.
Expand All @@ -23,16 +23,16 @@ type APIResponse struct {
Payload []byte `json:"-"`
}

// NewAPIResponse returns a new APIResonse object.
func NewAPIResponse(r *http.Response) *APIResponse {
// NewDefaultAPIResponse returns a new APIResonse object.
func NewDefaultAPIResponse(r *http.Response) *DefaultAPIResponse {

response := &APIResponse{Response: r}
response := &DefaultAPIResponse{Response: r}
return response
}

// NewAPIResponseWithError returns a new APIResponse object with the provided error message.
func NewAPIResponseWithError(errorMessage string) *APIResponse {
// NewDefaultAPIResponseWithError returns a new DefaultAPIResponse object with the provided error message.
func NewDefaultAPIResponseWithError(errorMessage string) *DefaultAPIResponse {

response := &APIResponse{Message: errorMessage}
response := &DefaultAPIResponse{Message: errorMessage}
return response
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ type ServerVariable struct {

// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
Url string
URL string
Description string
Variables map[string]ServerVariable
}
Expand Down Expand Up @@ -95,7 +95,7 @@ func NewConfiguration() *Configuration {
Servers: []ServerConfiguration{
{{/-first}}
{
Url: "{{{url}}}",
URL: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
Expand Down Expand Up @@ -132,13 +132,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}

// ServerUrl returns URL based on server settings
func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
if index < 0 || len(c.Servers) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
}
server := c.Servers[index]
url := server.Url
url := server.URL

// go through variables and replace placeholders
for name, variable := range server.Variables {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"net/http"
)

// APIResponse stores the API response returned by the server.
type APIResponse struct {
// DefaultAPIResponse stores the API response returned by the server.
type DefaultAPIResponse struct {
*http.Response `json:"-"`
Message string `json:"message,omitempty"`
// Operation is the name of the OpenAPI operation.
Expand All @@ -23,16 +23,16 @@ type APIResponse struct {
Payload []byte `json:"-"`
}

// NewAPIResponse returns a new APIResonse object.
func NewAPIResponse(r *http.Response) *APIResponse {
// NewDefaultAPIResponse returns a new DefaultAPIResponse object.
func NewDefaultAPIResponse(r *http.Response) *DefaultAPIResponse {

response := &APIResponse{Response: r}
response := &DefaultAPIResponse{Response: r}
return response
}

// NewAPIResponseWithError returns a new APIResponse object with the provided error message.
func NewAPIResponseWithError(errorMessage string) *APIResponse {
// NewDefaultAPIResponseWithError returns a new DefaultAPIResponse object with the provided error message.
func NewDefaultAPIResponseWithError(errorMessage string) *DefaultAPIResponse {

response := &APIResponse{Message: errorMessage}
response := &DefaultAPIResponse{Message: errorMessage}
return response
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public void simpleModelTest() {
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int64");
Assert.assertEquals(property1.name, "Id");
Assert.assertEquals(property1.name, "ID");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int64");
Assert.assertTrue(property1.hasMore);
Expand Down Expand Up @@ -105,7 +105,7 @@ public void listPropertyTest() {
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int64");
Assert.assertEquals(property1.name, "Id");
Assert.assertEquals(property1.name, "ID");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int64");
Assert.assertTrue(property1.hasMore);
Expand All @@ -115,7 +115,7 @@ public void listPropertyTest() {
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "urls");
Assert.assertEquals(property2.dataType, "[]string");
Assert.assertEquals(property2.name, "Urls");
Assert.assertEquals(property2.name, "URLs");
Assert.assertEquals(property2.baseType, "array");
Assert.assertFalse(property2.hasMore);
Assert.assertEquals(property2.containerType, "array");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

import static org.openapitools.codegen.utils.StringUtils.*;

import java.util.HashMap;
import java.util.Map;

public class StringUtilsTest {
// we'll assume that <i>underscore</i> (Twitter elephant bird) works fine
@Test
Expand All @@ -28,6 +31,18 @@ public void testCamelize() throws Exception {

Assert.assertEquals(camelize("123", true), "123");
Assert.assertEquals(camelize("$123", true), "$123");

Map<String, String> exc = new HashMap<String, String>();
exc.put("Id", "ID");
exc.put("Api", "API");
exc.put("Xml", "XML");
exc.put("Http", "HTTP");
Assert.assertEquals(camelize("name_id", exc), "NameID");
Assert.assertEquals(camelize("some-api", exc), "SomeAPI");
Assert.assertEquals(camelize("id-name", exc), "IDName");
Assert.assertEquals(camelize("id-name", true, exc), "idName");
Assert.assertEquals(camelize("xml-http-request", exc), "XMLHTTPRequest");
Assert.assertEquals(camelize("xml-http-request", true, exc), "xmlHTTPRequest");
}

@Test
Expand Down
Loading