Improve camelization in DefaultCodegen

This commit is contained in:
Tim Selman 2023-06-07 13:00:41 +02:00
parent fbe768bb9c
commit 80b6dd933f
2 changed files with 42 additions and 2 deletions

View File

@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
package org.openapitools.codegen; package org.openapitools.codegen;
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.Caffeine;
@ -5910,7 +5910,13 @@ public class DefaultCodegen implements CodegenConfig {
* @return camelized string * @return camelized string
*/ */
protected String removeNonNameElementToCamelCase(final String name, final String nonNameElementPattern) { protected String removeNonNameElementToCamelCase(final String name, final String nonNameElementPattern) {
String result = Arrays.stream(name.split(nonNameElementPattern)) String[] splitString = name.split(nonNameElementPattern);
if (splitString.length > 0) {
splitString[0] = lowerStartOfWord(splitString[0]);
}
String result = Arrays.stream(splitString)
.map(StringUtils::capitalize) .map(StringUtils::capitalize)
.collect(Collectors.joining("")); .collect(Collectors.joining(""));
if (result.length() > 0) { if (result.length() > 0) {
@ -5919,6 +5925,29 @@ public class DefaultCodegen implements CodegenConfig {
return result; return result;
} }
/**
* Puts the first letters to lowercase. If the word starts with multiple capital letters, all of them
* will be converted to lowercase.
* @param name string to be changed
* @return string starting with lowercase
*/
private String lowerStartOfWord(final String name) {
final StringBuilder result = new StringBuilder();
boolean isStartingBlock = true;
for (int i = 0; i < name.length(); i++) {
char current = name.charAt(i);
if (isStartingBlock && Character.isUpperCase(current)) {
current = Character.toLowerCase(current);
} else {
isStartingBlock = false;
}
result.append(current);
}
return result.toString();
}
@Override @Override
public String apiFilename(String templateName, String tag) { public String apiFilename(String templateName, String tag) {
String suffix = apiTemplateFiles().get(templateName); String suffix = apiTemplateFiles().get(templateName);

View File

@ -4722,4 +4722,15 @@ public class DefaultCodegenTest {
Assert.assertTrue(codegen.cliOptions.contains(expected)); Assert.assertTrue(codegen.cliOptions.contains(expected));
} }
@Test
public void testRemoveNonNameElementToCamelCase() {
final DefaultCodegen codegen = new DefaultCodegen();
final String alreadyCamelCase = "aVATRate";
Assert.assertEquals(codegen.removeNonNameElementToCamelCase(alreadyCamelCase), alreadyCamelCase);
final String startWithCapitals = "DELETE_Invoice";
Assert.assertEquals(codegen.removeNonNameElementToCamelCase(startWithCapitals), "deleteInvoice");
}
} }