Skip to content

Commit 0cfa3c5

Browse files
authored
[kotlin-spring] feature: Add x-extra-imports vendor extension (#24638)
* feat(kotlin-spring): implement x-extra-imports support for models and operations * update samples * add comment to template * implement changes from CR feedback
1 parent 6d46422 commit 0cfa3c5

7 files changed

Lines changed: 376 additions & 0 deletions

File tree

‎docs/generators/kotlin-spring.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
8787
|x-discriminator-value|Used with model inheritance to specify value for discriminator that identifies current model|MODEL|
8888
|x-field-extra-annotation|Custom annotation(s) to be added to property; accepts a string or list of strings|FIELD, OPERATION_PARAMETER|null
8989
|x-operation-extra-annotation|Custom annotation(s) to be added to operation; accepts a string or list of strings|OPERATION|null
90+
|x-extra-imports|Custom import(s) to add to the generated file that declares the annotated model, property, operation, or parameter (e.g. so custom annotations can be referenced by their short name); accepts a string or list of strings. Values are emitted verbatim (Kotlin alias imports supported) and only exact duplicates are removed|MODEL, FIELD, OPERATION, OPERATION_PARAMETER|null
9091
|x-pattern-message|Add this property whenever you need to customize the invalidation error message for the regex pattern of a variable|FIELD, OPERATION_PARAMETER|null
9192
|x-size-message|Add this property whenever you need to customize the invalidation error message for the size or length of a variable|FIELD, OPERATION_PARAMETER|null
9293
|x-minimum-message|Add this property whenever you need to customize the invalidation error message for the minimum value of a variable|FIELD, OPERATION_PARAMETER|null

‎modules/openapi-generator/src/main/java/org/openapitools/codegen/VendorExtension.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public enum VendorExtension {
2626
X_CLASS_EXTRA_ANNOTATION("x-class-extra-annotation", ExtensionLevel.MODEL, "Custom annotation(s) to be added to model; accepts a string or list of strings", null),
2727
X_FIELD_EXTRA_ANNOTATION("x-field-extra-annotation", Arrays.asList(ExtensionLevel.FIELD, ExtensionLevel.OPERATION_PARAMETER), "Custom annotation(s) to be added to property; accepts a string or list of strings", null),
2828
X_OPERATION_EXTRA_ANNOTATION("x-operation-extra-annotation", ExtensionLevel.OPERATION, "Custom annotation(s) to be added to operation; accepts a string or list of strings", null),
29+
X_EXTRA_IMPORTS("x-extra-imports", Arrays.asList(ExtensionLevel.MODEL, ExtensionLevel.FIELD, ExtensionLevel.OPERATION, ExtensionLevel.OPERATION_PARAMETER), "Custom import(s) to add to the generated file that declares the annotated model, property, operation, or parameter (e.g. so custom annotations can be referenced by their short name); accepts a string or list of strings. Values are emitted verbatim (Kotlin alias imports supported) and only exact duplicates are removed", null),
2930
X_VERSION_PARAM("x-version-param", ExtensionLevel.OPERATION_PARAMETER, "Marker property that tells that this parameter would be used for endpoint versioning. Applicable for headers & query params. true/false", null),
3031
X_PATTERN_MESSAGE("x-pattern-message", Arrays.asList(ExtensionLevel.FIELD, ExtensionLevel.OPERATION_PARAMETER), "Add this property whenever you need to customize the invalidation error message for the regex pattern of a variable", null),
3132
X_SIZE_MESSAGE("x-size-message", Arrays.asList(ExtensionLevel.FIELD, ExtensionLevel.OPERATION_PARAMETER), "Add this property whenever you need to customize the invalidation error message for the size or length of a variable", null),

‎modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,6 +1337,79 @@ public void addImportsToOneOfInterface(List<Map<String, String>> imports) {
13371337
}
13381338
}
13391339

1340+
/**
1341+
* Reads the {@code x-extra-imports} vendor extension from the given vendor-extension map and
1342+
* appends its values to {@code target}. The extension accepts either a single string or a list
1343+
* of strings; parsing is delegated to {@link #getObjectAsStringList(Object)} for consistency with
1344+
* how the sibling {@code x-*-extra-annotation} extensions are handled. Values are preserved
1345+
* verbatim (Kotlin alias imports are supported); no validation, trimming, or conflict detection is
1346+
* performed. Exact-duplicate handling is left to the caller's collection (typically a
1347+
* {@link LinkedHashSet} to keep insertion order while removing duplicates).
1348+
*
1349+
* @param vendorExtensions vendor extensions of a model, property, operation, or parameter (may be {@code null})
1350+
* @param target collection to which extracted import directives are added
1351+
*/
1352+
private void collectExtraImports(Map<String, Object> vendorExtensions, Collection<String> target) {
1353+
if (vendorExtensions == null) {
1354+
return;
1355+
}
1356+
target.addAll(getObjectAsStringList(vendorExtensions.get(VendorExtension.X_EXTRA_IMPORTS.getName())));
1357+
}
1358+
1359+
/**
1360+
* Appends the given import directives to an {@code imports}-style list (a list of maps each
1361+
* holding a single {@code "import"} entry, as rendered by the {@code {{#imports}}} template
1362+
* blocks), skipping directives whose exact text already appears in the list.
1363+
*
1364+
* @param imports existing import list to extend (must be mutable)
1365+
* @param extraImports import directives to add, in insertion order
1366+
*/
1367+
private void appendExtraImports(List<Map<String, String>> imports, Collection<String> extraImports) {
1368+
Set<String> existing = imports.stream()
1369+
.map(m -> m.get("import"))
1370+
.filter(Objects::nonNull)
1371+
.collect(Collectors.toCollection(HashSet::new));
1372+
for (String imp : extraImports) {
1373+
if (existing.add(imp)) {
1374+
Map<String, String> item = new HashMap<>();
1375+
item.put("import", imp);
1376+
imports.add(item);
1377+
}
1378+
}
1379+
}
1380+
1381+
@Override
1382+
public ModelsMap postProcessModels(ModelsMap objs) {
1383+
objs = super.postProcessModels(objs);
1384+
1385+
// Collect x-extra-imports declared on each model and its properties, and add them to the
1386+
// model file's import list so custom class/field annotations can be referenced by short name.
1387+
// Each ModelsMap corresponds to a single generated model file, so this stays file-scoped.
1388+
Set<String> extraImports = new LinkedHashSet<>();
1389+
for (ModelMap mo : objs.getModels()) {
1390+
CodegenModel cm = mo.getModel();
1391+
if (cm == null) {
1392+
continue;
1393+
}
1394+
collectExtraImports(cm.vendorExtensions, extraImports);
1395+
// allVars is the complete property set (own + inherited); vars is included for safety.
1396+
// The LinkedHashSet collapses any overlap between the two lists.
1397+
Stream.of(cm.vars, cm.allVars)
1398+
.filter(Objects::nonNull)
1399+
.flatMap(List::stream)
1400+
.forEach(p -> collectExtraImports(p.vendorExtensions, extraImports));
1401+
}
1402+
if (!extraImports.isEmpty()) {
1403+
List<Map<String, String>> imports = objs.getImports();
1404+
if (imports == null) {
1405+
imports = new ArrayList<>();
1406+
objs.setImports(imports);
1407+
}
1408+
appendExtraImports(imports, extraImports);
1409+
}
1410+
return objs;
1411+
}
1412+
13401413
@Override
13411414
public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs) {
13421415
objs = super.postProcessAllModels(objs);
@@ -1689,6 +1762,43 @@ public void setReturnContainer(final String returnContainer) {
16891762

16901763
handleImplicitHeaders(objs);
16911764

1765+
// Collect x-extra-imports declared on operations and their parameters for this API group.
1766+
// Grouping (by tag or by path segment, per useTags) is already reflected in this OperationsMap,
1767+
// so the imports are scoped to exactly the API file(s) that render these operations. They are
1768+
// exposed under a dedicated key (not the shared "imports" list) so that only templates which
1769+
// render the related annotations (api.mustache / apiInterface.mustache) emit them, while
1770+
// delegate, controller-wrapper, service and test templates do not.
1771+
if (operations != null) {
1772+
Set<String> operationExtraImports = new LinkedHashSet<>();
1773+
for (CodegenOperation operation : operations.getOperation()) {
1774+
collectExtraImports(operation.vendorExtensions, operationExtraImports);
1775+
if (operation.allParams != null) {
1776+
operation.allParams.forEach(param -> collectExtraImports(param.vendorExtensions, operationExtraImports));
1777+
}
1778+
// Implicit header params are moved out of allParams by handleImplicitHeaders above,
1779+
// so scan them separately to avoid dropping their declared imports.
1780+
if (operation.implicitHeadersParams != null) {
1781+
operation.implicitHeadersParams.forEach(param -> collectExtraImports(param.vendorExtensions, operationExtraImports));
1782+
}
1783+
}
1784+
// Drop any import already present in the shared imports list (e.g. produced from an
1785+
// operation's types) so the file keeps the documented once-per-file deduplication.
1786+
Set<String> existingImports = objs.getImports().stream()
1787+
.map(m -> m.get("import"))
1788+
.filter(Objects::nonNull)
1789+
.collect(Collectors.toCollection(HashSet::new));
1790+
operationExtraImports.removeAll(existingImports);
1791+
if (!operationExtraImports.isEmpty()) {
1792+
List<Map<String, String>> extraImportList = new ArrayList<>();
1793+
for (String imp : operationExtraImports) {
1794+
Map<String, String> item = new HashMap<>();
1795+
item.put("import", imp);
1796+
extraImportList.add(item);
1797+
}
1798+
objs.put("operationExtraImports", extraImportList);
1799+
}
1800+
}
1801+
16921802
return objs;
16931803
}
16941804

@@ -1777,6 +1887,7 @@ public List<VendorExtension> getSupportedVendorExtensions() {
17771887
extensions.add(VendorExtension.X_DISCRIMINATOR_VALUE);
17781888
extensions.add(VendorExtension.X_FIELD_EXTRA_ANNOTATION);
17791889
extensions.add(VendorExtension.X_OPERATION_EXTRA_ANNOTATION);
1890+
extensions.add(VendorExtension.X_EXTRA_IMPORTS);
17801891
extensions.add(VendorExtension.X_PATTERN_MESSAGE);
17811892
extensions.add(VendorExtension.X_SIZE_MESSAGE);
17821893
extensions.add(VendorExtension.X_MINIMUM_MESSAGE);

‎modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ package {{package}}
22

33
{{#imports}}import {{import}}
44
{{/imports}}
5+
{{#operationExtraImports}}import {{{import}}}
6+
{{/operationExtraImports}}
7+
{{! Dedicated key (not the shared imports list) so these x-extra-imports render only in files that
8+
emit x-operation-extra-annotation. The OperationsMap imports list is shared with apiDelegate,
9+
service, api_test, etc., which don't; keeping them here avoids leaking unused imports there. }}
510
{{#swagger2AnnotationLibrary}}
611
import io.swagger.v3.oas.annotations.*
712
import io.swagger.v3.oas.annotations.enums.*

‎modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ package {{package}}
77

88
{{#imports}}import {{import}}
99
{{/imports}}
10+
{{#operationExtraImports}}import {{{import}}}
11+
{{/operationExtraImports}}
12+
{{! Dedicated key (not the shared imports list) so these x-extra-imports render only in files that
13+
emit x-operation-extra-annotation. The OperationsMap imports list is shared with apiDelegate,
14+
service, api_test, etc., which don't; keeping them here avoids leaking unused imports there. }}
1015
{{#swagger2AnnotationLibrary}}
1116
import io.swagger.v3.oas.annotations.*
1217
import io.swagger.v3.oas.annotations.enums.*

0 commit comments

Comments
 (0)