OpenAPITools / openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
https://openapi-generator.tech
Apache License 2.0
21.29k stars 6.44k forks source link

[BUG] Java enum values are messed up #19438

Open mortenegelund opened 2 weeks ago

mortenegelund commented 2 weeks ago
Description

When enum values are parsed with the Java parser, they get messed up in the generated code.

For example:

openapi-generator version

Version 7.8.0

Suggested fix

This bug has been introduced with https://github.com/OpenAPITools/openapi-generator/pull/18338

AbstractJavaCodeGen.java, line 1913:

    @Override
    public String toEnumVarName(String value, String datatype) {
        if (enumNameMapping.containsKey(value)) {
            return enumNameMapping.get(value);
        }

        if (value.length() == 0) {
            return "EMPTY";
        }

        // for symbol, e.g. $, #
        if (getSymbolName(value) != null) {
            return getSymbolName(value).toUpperCase(Locale.ROOT);
        }

        if (" ".equals(value)) {
            return "SPACE";
        }

        // number
        if ("Integer".equals(datatype) || "Long".equals(datatype) ||
                "Float".equals(datatype) || "Double".equals(datatype) || "BigDecimal".equals(datatype)) {
            String varName = "NUMBER_" + value;
            varName = varName.replaceAll("-", "MINUS_");
            varName = varName.replaceAll("\\+", "PLUS_");
            varName = varName.replaceAll("\\.", "_DOT_");
            return varName;
        }

        // string
        String var = value.replaceAll("\\W+", "_").toUpperCase(Locale.ROOT);
        if (var.matches("\\d.*")) {
            var = "_" + var;
        }
        return this.toVarName(var); <----------------Should be changed to "return var;"
    }
Related issues/PRs

https://github.com/OpenAPITools/openapi-generator/pull/18338

jpfinne commented 2 weeks ago

Same issue as #19204

There 2 workarounds: x-enum-varnames in the contract or enumNameMappings option

Some generators have the enumPropertyNaming option. original could solve your specific issue but you would loose the conversion to uppercase. Unfortunately no java implementation yet. There is #19277

mortenegelund commented 2 weeks ago

There are no hard enum naming conventions in Java. I suggest enum parsing should be done at an absolute minimum level just to avoid syntax errors.