Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix deduplication
Browse files Browse the repository at this point in the history
noanflaherty committed Oct 18, 2024

Verified

This commit was signed with the committer’s verified signature.
serban300 Serban Iorga
1 parent 20e6a71 commit 0ed93df
Showing 3 changed files with 42 additions and 3 deletions.
12 changes: 9 additions & 3 deletions generators/pythonv2/codegen/src/ast/PythonFile.ts
Original file line number Diff line number Diff line change
@@ -62,18 +62,24 @@ export class PythonFile extends AstNode {
const references = this.getReferences();

// Deduplicate references by their fully qualified paths
const uniqueReferences = new Map<string, { modulePath: string[]; references: Reference[] }>();
const uniqueReferences = new Map<
string,
{ modulePath: string[]; references: Reference[]; referenceNames: Set<string> }
>();
for (const reference of references) {
const fullyQualifiedPath = reference.getFullyQualifiedModulePath();
const existingRefs = uniqueReferences.get(fullyQualifiedPath);
const referenceName = reference.getName();
if (existingRefs) {
if (!existingRefs.references.includes(reference)) {
if (!existingRefs.referenceNames.has(referenceName)) {
existingRefs.references.push(reference);
existingRefs.referenceNames.add(referenceName);
}
} else {
uniqueReferences.set(fullyQualifiedPath, {
modulePath: reference.getModulePath(),
references: [reference]
references: [reference],
referenceNames: new Set([referenceName])
});
}
}
24 changes: 24 additions & 0 deletions generators/pythonv2/codegen/src/ast/__test__/PythonFile.test.ts
Original file line number Diff line number Diff line change
@@ -218,4 +218,28 @@ describe("PythonFile", () => {
file.write(writer);
expect(await writer.toStringFormatted()).toMatchSnapshot();
});

it("Ensure we don't duplicate imports", async () => {
const file = python.file({
moduleName: "test_module",
path: ["test"],
name: "test_file"
});

const varAField = python.field({
name: "var_a",
type: python.Type.list(python.Type.str())
});

const varBField = python.field({
name: "var_b",
type: python.Type.list(python.Type.str())
});

file.addStatement(varAField);
file.addStatement(varBField);

file.write(writer);
expect(await writer.toStringFormatted()).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
@@ -75,6 +75,15 @@ cars: List[Car] = [Car(), Car()]
"
`;

exports[`PythonFile > Ensure we don't duplicate imports 1`] = `
"from typing import List
var_a: List[str]
var_b: List[str]
"
`;

exports[`PythonFile > Multiple imports from the same module should work 1`] = `
"from typing import Union, List, Set

0 comments on commit 0ed93df

Please sign in to comment.