Skip to content
Open
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 @@ -31,6 +31,7 @@
import org.apache.commons.io.IOCase;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.api.*;
import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
Expand Down Expand Up @@ -1656,7 +1657,7 @@ private OperationsMap processOperations(CodegenConfig config, String tag, List<C
allImports.addAll(op.imports);
}

Map<String, String> mappings = getAllImportsMappings(allImports);
Set<Pair<String, String>> mappings = getAllImportMappings(allImports);
Set<Map<String, String>> imports = toImportsObjects(mappings);

//Some codegen implementations rely on a list interface for the imports
Expand Down Expand Up @@ -1734,6 +1735,16 @@ private Map<String, String> getAllImportsMappings(Set<String> allImports) {
return result;
}

private Set<Pair<String, String>> getAllImportMappings(Set<String> allImports) {
return allImports.stream().map(nextImport -> {
String mapping = config.importMapping().get(nextImport);
if (mapping != null) {
return Pair.of(mapping, nextImport);
}
return Pair.of(config.toModelImport(nextImport), nextImport);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Operation import aggregation now collapses composed imports to a single toModelImport(...) result, so generators that depend on toModelImportMap(...) expanding one symbol into multiple imports can lose required imports in generated operation files.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java, line 1744:

<comment>Operation import aggregation now collapses composed imports to a single `toModelImport(...)` result, so generators that depend on `toModelImportMap(...)` expanding one symbol into multiple imports can lose required imports in generated operation files.</comment>

<file context>
@@ -1734,6 +1735,16 @@ private Map<String, String> getAllImportsMappings(Set<String> allImports) {
+            if (mapping != null) {
+                return Pair.of(mapping, nextImport);
+            }
+            return Pair.of(config.toModelImport(nextImport), nextImport);
+        }).collect(Collectors.toSet());
+    }
</file context>

}).collect(Collectors.toSet());
}

/**
* Using an import map created via {@link #getAllImportsMappings(Set)} to build a list import objects.
* The import objects have two keys: import and classname which hold the key and value of the initial map entry.
Expand All @@ -1755,6 +1766,20 @@ private Set<Map<String, String>> toImportsObjects(Map<String, String> mappedImpo
return result;
}

private Set<Map<String, String>> toImportsObjects(Set<Pair<String, String>> importPairs) {
Set<Map<String, String>> result = new TreeSet<>(
Comparator.comparing(o -> o.get("classname"))
);

importPairs.forEach((pair) -> {
Map<String, String> im = new LinkedHashMap<>();
im.put("import", pair.getLeft());
im.put("classname", pair.getRight());
result.add(im);
});
return result;
}

private ModelsMap processModels(CodegenConfig config, Map<String, Schema> definitions) {
ModelsMap objs = new ModelsMap();
objs.put("package", config.modelPackage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
Expand Down Expand Up @@ -476,13 +477,13 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap operations, L
operations.put("hasSomeEncodableParams", hasSomeEncodableParams);

// Add additional filename information for model imports in the services
List<Map<String, String>> imports = operations.getImports();
for (Map<String, String> im : imports) {
List<Map<String, String>> mergedImports = mergeImports(operations.getImports());
for (Map<String, String> im : mergedImports) {
// This property is not used in the templates any more, subject for removal
im.put("filename", im.get("import"));
im.put("classname", im.get("classname"));
}

operations.setImports(mergedImports);
return operations;
}

Expand Down Expand Up @@ -580,6 +581,28 @@ private List<Map<String, String>> toTsImports(CodegenModel cm, Set<String> impor
return tsImports;
}

/**
* Merge imports that belong to the same file
*/
private List<Map<String, String>> mergeImports(List<Map<String, String>> imports) {
Map<String, String> importLookup = new HashMap<>();
imports.forEach(importMap -> {
String importPackage = importMap.get("import");
String importType = importMap.get("classname");
String existingImportType = importLookup.get(importPackage);
if (existingImportType != null && !existingImportType.equals(importType)) {
String newImportType = String.join(", ", existingImportType, importType);
importLookup.put(importPackage, newImportType);
} else {
importLookup.put(importPackage, importType);
}
});

return importLookup.entrySet().stream()
.map(entry -> new HashMap<>(Map.of("import", entry.getKey(), "classname", entry.getValue())))
.collect(Collectors.toList());
}

@Override
public String toApiName(String name) {
if (name.length() == 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import org.openapitools.codegen.*;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.model.OperationMap;
import org.openapitools.codegen.model.OperationsMap;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
Expand All @@ -19,12 +21,13 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;


@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypeScriptAngularClientCodegenTest {
@Test
Expand Down Expand Up @@ -124,7 +127,6 @@ public void testOperationIdParser() {

CodegenOperation co1 = codegen.fromOperation("/another-fake/dummy/", "get", operation1, null);
org.testng.Assert.assertEquals(co1.operationId, "_123testSpecialTags");

}

@Test
Expand All @@ -148,7 +150,6 @@ public void testSnapshotVersion() {
codegen.preprocessOpenAPI(openAPI);

Assert.assertTrue(codegen.getNpmVersion().matches("^3.0.0-M1-SNAPSHOT.[0-9]{12}$"));

}

@Test
Expand All @@ -172,7 +173,6 @@ public void testWithoutSnapshotVersion() {
codegen.preprocessOpenAPI(openAPI);

Assert.assertTrue(codegen.getNpmVersion().matches("^3.0.0-M1$"));

}

@Test
Expand Down Expand Up @@ -500,9 +500,9 @@ public void testOpenIdCredentialsAreSet() throws IOException {

// WHEN
final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("typescript-angular")
.setInputSpec(specPath)
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
.setGeneratorName("typescript-angular")
.setInputSpec(specPath)
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));

final ClientOptInput clientOptInput = configurator.toClientOptInput();

Expand All @@ -514,4 +514,27 @@ public void testOpenIdCredentialsAreSet() throws IOException {
String credentialsSet = "localVarHeaders = this.configuration.addCredentialToHeaders('oidc', 'Authorization', localVarHeaders, 'Bearer ');";
assertThat(fileContents).contains(credentialsSet);
}

@Test
public void testMergingImports() {
TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen();

List<Map<String, String>> imports = new ArrayList<>();
imports.add(Map.of("classname", "type1", "import", "npmPackage"));
imports.add(Map.of("classname", "type2", "import", "npmPackage"));
imports.add(Map.of("classname", "type3", "import", "npmPackage2"));
OperationMap operation = new OperationMap();
operation.setClassname("classname");
operation.setOperation(List.of());
OperationsMap operationsMap = new OperationsMap();
operationsMap.setImports(imports);
operationsMap.setOperation(operation);

OperationsMap result = codegen.postProcessOperationsWithModels(operationsMap, List.of());

assertThat(result.getImports()).containsExactlyInAnyOrder(
Map.of("classname", "type1, type2", "filename", "npmPackage", "import", "npmPackage"),
Map.of("classname", "type3", "filename", "npmPackage2", "import", "npmPackage2")
);
}
}
Loading