openrewrite / rewrite

Automated mass refactoring of source code.
https://docs.openrewrite.org
Apache License 2.0
1.99k stars 294 forks source link

YAML recipes: new option to specify yaml pattern files to modify #656

Closed murdos closed 3 years ago

murdos commented 3 years ago

Use case: I'm using spring-boot, and have a yml configuration file per profile:

I would like to apply different rules and thus recipes to each profile (that could be translated to file pattern). This doesn't seems possible with the provided recipes ChangeKey, DeleteProperty, ...

jkschneider commented 3 years ago

For now at least until we see more of these cases, I hope we can use single source applicability tests to solve this use case. I'm adding a new one that handles this request and other similar requests (like limiting a recipe to run on just some particular module). It would require you to write a recipe in code to use:

import org.openrewrite.HasSourcePath; // from rewrite-core

public class ChangeAppNameInDevProfile extends Recipe {
    @Override
    public String getDisplayName() {
        return "Rename all applications to 'my app'";
    }

    public ChangeAppNameInDevProfile() {
        doNext(new ChangeValue("spring/application/name", "my app"));
    }

    @Override
    protected TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
        return new HasSourcePath<>("**/application-dev.yml");
    }
}
murdos commented 3 years ago

Thanks for adding HasSourcePath that is already really helpful.

Still I was thinking that for all recipes that are related to files (XML, YAML, Properties), the main use case is hardly to change all {yaml,properties,xml} files in your project the same way. With Java or Maven recipes, things are differents because you have only one pom.xml, or each class has a unique FQDN so you can use MethodMatcher, AnnotationMatcher, ... to refine the scope of your recipe. And having to write your own java recipe for every use IMO is too bad, when you could use a declarative recipe.

Would you accept a PR that add an additional fileMatcher option to most common YAML, XML and properties recipes, as demonstrated here for properties: https://github.com/openrewrite/rewrite/pull/690 ?

murdos commented 3 years ago

@jkschneider : ping. I'm not sure you have seen my question in the previous comment.