diff --git a/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java b/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java index c73b39c09a2..aae74c3977d 100644 --- a/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java +++ b/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java @@ -45,13 +45,7 @@ protected CtRole getRole() { @Override public CtPackage put(String simpleName, CtPackage pack) { - if (pack == null) { - return null; - } - // they are the same - if (CtPackageImpl.this.getQualifiedName().equals(pack.getQualifiedName())) { - addAllTypes(pack, CtPackageImpl.this); - addAllPackages(pack, CtPackageImpl.this); + if (pack == null || pack == CtPackageImpl.this) { return null; } diff --git a/src/test/java/spoon/reflect/factory/PackageFactoryTest.java b/src/test/java/spoon/reflect/factory/PackageFactoryTest.java new file mode 100644 index 00000000000..13cb1897fa1 --- /dev/null +++ b/src/test/java/spoon/reflect/factory/PackageFactoryTest.java @@ -0,0 +1,31 @@ +package spoon.reflect.factory; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; + +import spoon.Launcher; +import spoon.reflect.declaration.CtPackage; +import spoon.test.GitHubIssue; + +class PackageFactoryTest { + + @GitHubIssue(issueNumber = 4764, fixed = true) + void getOrCreate_returnsNestedPackageStructure_whenQualifiedNameRepeatsSimpleName() { + // contract: A qualified name that is simply repetitions of a single simple name results in the expected + // nested package structure + + PackageFactory factory = new Launcher().getFactory().Package(); + String topLevelPackageName = "spoon"; + String nestedPackageName = topLevelPackageName + "." + topLevelPackageName; + + CtPackage packageWithDuplicatedSimpleNames = factory.getOrCreate(nestedPackageName); + CtPackage topLevelPackage = factory.get(topLevelPackageName); + + assertThat(topLevelPackage.getQualifiedName(), equalTo(topLevelPackageName)); + assertThat(packageWithDuplicatedSimpleNames.getQualifiedName(), equalTo(nestedPackageName)); + + assertThat(topLevelPackage.getPackage(topLevelPackageName), sameInstance(packageWithDuplicatedSimpleNames)); + assertThat(packageWithDuplicatedSimpleNames.getParent(), sameInstance(topLevelPackage)); + } +} \ No newline at end of file