Skip to content

feat: merge categories which have matching roots #5288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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 @@ -33,7 +33,23 @@ public class CategoryDescriptor {
@NlsRewrite.DisplayName
String displayName;

String packageName;
/**
* Represents the part of the package under the root packages collected in {@link #rootPackages}
* If a category contains the packages "org.openrewrite.java" and "com.company.java" this will become "java"
*/
String subPackageName;

/**
* Backwards compatibility method for retrieving the packageName
* which has been changed to only the subPackage name ("org.openrewrite.java" becomes "java")
*
* @return the sub-package name of this category descriptor.
* @deprecated Use {@link #getSubPackageName()} instead
*/
@Deprecated
public String getPackageName() {
return subPackageName;
}

@Language("markdown")
@NlsRewrite.Description
Expand All @@ -43,7 +59,7 @@ public class CategoryDescriptor {
boolean root;

/**
* Defines the sort order for category descriptors of the same {@link #packageName}. The description, tags, and root values of the highest
* Defines the sort order for category descriptors of the same {@link #subPackageName}. The description, tags, and root values of the highest
* priority category descriptor for a given package name will be used.
* <p/>
* Lower values have higher priority. The default value is {@link #LOWEST_PRECEDENCE}, indicating the lowest priority
Expand All @@ -52,4 +68,6 @@ public class CategoryDescriptor {
int priority;

boolean synthetic;

Set<String> rootPackages;
Copy link
Member

Choose a reason for hiding this comment

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

Something looks suspicious about this to me. We shouldn't have both packageName and Set of rootPackages. Which of the set of rootPackages does packageName represent?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

packageName does not include the root so that we can merge the packages together
while the rootPackages contains all the know subset of roots.

For example org.openrewrite.path.to.subcategory has a packageName of path.to.subcategory and a rootPackages of listof(org.openrewrite)

Copy link
Contributor

Choose a reason for hiding this comment

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

I guess we should rename packageName then, to avoid this confusion.

}
95 changes: 72 additions & 23 deletions rewrite-core/src/main/java/org/openrewrite/config/CategoryTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ private CategoryTree(G group, CategoryDescriptor descriptor) {
public static class Root<G> extends CategoryTree<G> {
private static final CategoryDescriptor ROOT_DESCRIPTOR = new CategoryDescriptor(
"ε", "", "", emptySet(), true,
CategoryDescriptor.LOWEST_PRECEDENCE, true);
CategoryDescriptor.LOWEST_PRECEDENCE, true, emptySet());

private Root() {
super();
Expand Down Expand Up @@ -96,9 +96,13 @@ public CategoryTree.Root<G> putRecipes(G group, RecipeDescriptor... recipes) {
}

public synchronized CategoryTree.Root<G> putCategories(G group, CategoryDescriptor... categories) {

synchronized (lock) {
List<String> rootGroups = Arrays.stream(categories).filter(CategoryDescriptor::isRoot)
.map(CategoryDescriptor::getSubPackageName)
.collect(toList());
for (CategoryDescriptor category : categories) {
findOrAddCategory(group, category);
findOrAddCategory(group, category, rootGroups);
}
}
return this;
Expand Down Expand Up @@ -165,11 +169,11 @@ public Integer getRecipeCount() {
}

public @Nullable CategoryTree<G> getCategory(String subcategory) {
String packageName = getDescriptor().getPackageName();
String packageName = getDescriptor().getSubPackageName();
synchronized (lock) {
String[] split = subcategory.split("\\.", 2);
for (CategoryTree<G> t : getCategories(false, true)) {
String tPackage = t.getDescriptor().getPackageName();
String tPackage = t.getDescriptor().getSubPackageName();
int endIndex = tPackage.indexOf('.', packageName.length() + 1);
String test = tPackage.substring(
packageName.isEmpty() ? 0 : packageName.length() + 1,
Expand Down Expand Up @@ -202,7 +206,7 @@ public CategoryTree<G> getCategoryOrThrow(String subcategory) {
CategoryTree<G> subtree = getCategory(subcategory);
if (subtree == null) {
throw new IllegalArgumentException("No subcategory of " +
getDescriptor().getPackageName() + " named '" + subcategory + "'");
getDescriptor().getSubPackageName() + " named '" + subcategory + "'");
}
return subtree;
}
Expand Down Expand Up @@ -249,9 +253,36 @@ public CategoryTree<G> getCategoryOrThrow(String... subcategories) {
return null;
}

CategoryTree<G> findOrAddCategory(G group, CategoryDescriptor category) {
String packageName = getDescriptor().getPackageName();
String categoryPackage = category.getPackageName();
CategoryTree<G> findOrAddCategory(G group, CategoryDescriptor category, List<String> rootGroups) {
String packageName = getDescriptor().getSubPackageName();
String categoryPackage = category.getSubPackageName();
Set<String> roots = new HashSet<>();
if (category.isRoot()) {
return this;
} else {
List<String> possibleRoots = rootGroups.stream()
.filter(categoryPackage::startsWith).collect(toList());
int elementCount = possibleRoots
.stream().map(s -> s.length() - s.replace(".", "").length())
.max(Comparator.comparingInt(s -> s)).orElse(0);

possibleRoots.stream().filter(s -> s.length() - s.replace(".", "").length() == elementCount)
.forEach(s -> roots.add(s));

if (!possibleRoots.isEmpty()) {
String rootPrefix = possibleRoots.get(0);
categoryPackage = categoryPackage.replace(rootPrefix, "");

if (categoryPackage.startsWith(".")) {
categoryPackage = categoryPackage.substring(1);
}
category = category.withSubPackageName(categoryPackage);

String finalCategoryPackage = categoryPackage;
subtrees.stream().filter(t -> finalCategoryPackage.startsWith(t.getDescriptor().getSubPackageName())).collect(toList())
.forEach(s -> roots.addAll(s.getDescriptor().getRootPackages()));
}
}

// same category with a potentially different descriptor coming from this group
if (categoryPackage.equals(packageName)) {
Expand All @@ -272,7 +303,7 @@ CategoryTree<G> findOrAddCategory(G group, CategoryDescriptor category) {
if (packageName.isEmpty() || (categoryPackage.startsWith(packageName + ".") &&
categoryPackage.charAt(packageName.length()) == '.')) {
for (CategoryTree<G> subtree : subtrees) {
String subtreePackage = subtree.getDescriptor().getPackageName();
String subtreePackage = subtree.getDescriptor().getSubPackageName();
if (subtreePackage.equals(categoryPackage) || categoryPackage.startsWith(subtreePackage + ".")) {
if (!subtree.groups.contains(group)) {
subtree.groups.add(0, group);
Expand All @@ -283,16 +314,23 @@ CategoryTree<G> findOrAddCategory(G group, CategoryDescriptor category) {
emptySet(),
false,
CategoryDescriptor.LOWEST_PRECEDENCE,
true
true,
roots
));
} else {
CategoryDescriptor groupCategoryDescriptor = subtree.descriptorsByGroup.get(group);
Set<String> knownRootPackages = groupCategoryDescriptor.getRootPackages();
knownRootPackages.addAll(roots);
groupCategoryDescriptor.withRootPackages(knownRootPackages);
subtree.descriptorsByGroup.put(group, groupCategoryDescriptor);
}
return subtree.findOrAddCategory(group, category);
return subtree.findOrAddCategory(group, category, rootGroups);
}
}

String subpackage = packageName.isEmpty() ?
category.getPackageName() :
category.getPackageName().substring(packageName.length() + 1);
category.getSubPackageName() :
category.getSubPackageName().substring(packageName.length() + 1);
if (subpackage.contains(".")) {
String displayName = subpackage.substring(0, subpackage.indexOf('.'));

Expand All @@ -309,8 +347,9 @@ CategoryTree<G> findOrAddCategory(G group, CategoryDescriptor category) {
emptySet(),
false,
CategoryDescriptor.LOWEST_PRECEDENCE,
true
)).findOrAddCategory(group, category);
true,
roots
), rootGroups).findOrAddCategory(group, category, rootGroups);
}

// a direct subcategory of this category
Expand All @@ -319,7 +358,7 @@ CategoryTree<G> findOrAddCategory(G group, CategoryDescriptor category) {
return subtree;
} else {
throw new IllegalStateException("Attempted to add a category with package '" +
category.getPackageName() + "' as a subcategory of '" +
category.getSubPackageName() + "' as a subcategory of '" +
packageName + "'. This represents a bug in CategoryTree, as " +
"it should not be possible to add a category to a CategoryTree root " +
"that cannot be placed somewhere in the tree.");
Expand All @@ -335,15 +374,17 @@ void addRecipe(G group, RecipeDescriptor recipe) {
"a package, but it did not.");
}
String category = recipe.getName().substring(0, recipe.getName().lastIndexOf('.'));
List<String> rootPackageNames = this.getRootPackageNames();
CategoryTree<G> categoryTree = findOrAddCategory(group, new CategoryDescriptor(
StringUtils.capitalize(category.substring(category.lastIndexOf('.') + 1)),
category,
"",
emptySet(),
false,
CategoryDescriptor.LOWEST_PRECEDENCE,
true
));
true,
emptySet()
), rootPackageNames);
categoryTree.recipesByGroup.computeIfAbsent(group, g -> new CopyOnWriteArrayList<>()).add(recipe);
}

Expand Down Expand Up @@ -384,6 +425,13 @@ public Collection<CategoryTree<G>> getCategories() {
return getCategories(true, true);
}

public List<String> getRootPackageNames() {
return getCategories(false, false)
.stream().map(i -> i.getDescriptor().getRootPackages())
.flatMap(Set::stream)
.collect(toList());
}

/**
* Used to recursively navigate the whole category tree without
* any advance knowledge of what categories exist.
Expand Down Expand Up @@ -423,12 +471,13 @@ public Collection<CategoryTree<G>> getCategories(boolean omitCategoryRoots,
public CategoryDescriptor getDescriptor() {
return new CategoryDescriptor(
"Core",
parent.getPackageName() + "." + CORE,
parent.getSubPackageName() + "." + CORE,
"",
emptySet(),
false,
CategoryDescriptor.LOWEST_PRECEDENCE,
true
true,
emptySet()
);
}

Expand All @@ -441,7 +490,7 @@ public Map<G, Collection<RecipeDescriptor>> getRecipesByGroup() {

@Override
public String toString() {
return "CategoryTree{packageName=" + getDescriptor().getPackageName() + "}";
return "CategoryTree{subPackageName=" + getDescriptor().getSubPackageName() + "}";
}

void toString(StringJoiner out,
Expand All @@ -460,7 +509,7 @@ void toString(StringJoiner out,
line.append("|-");
}
line.append(descriptor.isRoot() ? "√" : "\uD83D\uDCC1");
String packageName = descriptor.getPackageName().isEmpty() ? "ε" : descriptor.getPackageName();
String packageName = descriptor.getSubPackageName().isEmpty() ? "ε" : descriptor.getSubPackageName();
switch (printOptions.getNameStyle()) {
case DISPLAY_NAME:
line.append(descriptor.getDisplayName());
Expand All @@ -469,7 +518,7 @@ void toString(StringJoiner out,
line.append(packageName);
break;
case BOTH:
if (descriptor.getPackageName().isEmpty()) {
if (descriptor.getSubPackageName().isEmpty()) {
line.append(packageName);
} else {
line.append(descriptor.getDisplayName()).append(" (").append(packageName).append(')');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@
import java.util.function.Consumer;
import java.util.stream.Stream;

import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.*;
import static java.util.stream.Collectors.toList;
import static org.openrewrite.RecipeSerializer.maybeAddKotlinModule;
import static org.openrewrite.Tree.randomId;
Expand Down Expand Up @@ -529,7 +528,7 @@ public Collection<CategoryDescriptor> listCategoryDescriptors() {
boolean root = c.containsKey("root") && (Boolean) c.get("root");
int priority = c.containsKey("priority") ? (Integer) c.get("priority") : CategoryDescriptor.DEFAULT_PRECEDENCE;

return new CategoryDescriptor(name, packageName, description, tags, root, priority, false);
return new CategoryDescriptor(name, packageName, description, tags, root, priority, false, emptySet());
})
.collect(toList());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

import static java.util.Collections.emptyList;
Expand Down Expand Up @@ -119,20 +120,10 @@ private static RecipeDescriptor recipeDescriptor(String packageName) {
void removeCategory() {
CategoryTree.Root<Group> ct = categoryTree();
ct.removeAll(Group2);
assertThat(ct.getCategories().stream().map(sub -> sub.getDescriptor().getPackageName()))
assertThat(ct.getCategories().stream().map(sub -> sub.getDescriptor().getSubPackageName()))
.doesNotContain("io.moderne.rewrite", "io.moderne.cloud", "io.moderne");
}

@Test
void categoryRoots() {
CategoryTree.Root<Group> ct = categoryTree();
assertThat(ct.getCategories().stream().map(sub -> sub.getDescriptor().getPackageName()))
.contains(
"io.moderne.rewrite", "io.moderne.cloud", // because "io.moderne" is marked as a root
"org.openrewrite" // because "org" is marked as a root
);
}

@Test
void getCategory() {
CategoryTree.Root<Group> ct = categoryTree();
Expand Down Expand Up @@ -171,10 +162,36 @@ void getRecipeGroup() {
.isEqualTo(Group1);
}

@Test
void mergeRootCategory() {
CategoryTree.Root<Integer> categoryTree = CategoryTree.build();
categoryTree
.putCategories(2, categoryRootDescriptor("io.moderne"), categoryRootDescriptor("org.openrewrite"), categoryDescriptor("org.openrewrite.java.test"), categoryDescriptor("io.moderne.java.test"))
.putRecipes(2, recipeDescriptor("org.openrewrite.java.test"), recipeDescriptor("io.moderne.java.test"));


assertThat(categoryTree.getCategory("java.test")).isNotNull();
assertThat(categoryTree.getCategory("org.openrewrite")).isNull();
assertThat(categoryTree.getCategory("org")).isNull();
assertThat(categoryTree.getCategory("io.moderne")).isNull();
assertThat(categoryTree.getCategory("io")).isNull();

assertThat(categoryTree.getCategory("java.test").getRecipes()).containsAll(List.of(
recipeDescriptor("org.openrewrite.java.test"),
recipeDescriptor("io.moderne.java.test")
));
}

private static CategoryDescriptor categoryDescriptor(String packageName) {
return new CategoryDescriptor(StringUtils.capitalize(packageName.substring(packageName.lastIndexOf('.') + 1)),
packageName, "", emptySet(),
false, CategoryDescriptor.DEFAULT_PRECEDENCE, false);
false, CategoryDescriptor.DEFAULT_PRECEDENCE, false, emptySet());
}

private static CategoryDescriptor categoryRootDescriptor(String packageName) {
return new CategoryDescriptor(StringUtils.capitalize(packageName.substring(packageName.lastIndexOf('.') + 1)),
packageName, "", emptySet(),
true, CategoryDescriptor.DEFAULT_PRECEDENCE, false, emptySet());
}

enum Group {
Expand Down
Loading