Writing recipes over multiple source file types
Sometimes we need to examine multiple source files or multiple types of source files to make a decision in a visitor about whether we intend to make a change. For example, we could be looking for a particular condition to be present in a Maven POM file, and if the condition is met alter an application property in a YAML file.
Use the visit(List<SourceFile> before, ExecutionContext ctx) method on Recipe to iterate over and maintain decision state, and then ListUtils.map to execute the transformation.
1
package org.openrewrite;
2
3
import org.openrewrite.internal.ListUtils;
4
import org.openrewrite.maven.tree.Maven;
5
import org.openrewrite.yaml.YamlVisitor;
6
7
import java.util.List;
8
9
public class MavenYamlRecipe extends Recipe {
10
@Override
11
public String getDisplayName() {
12
return "Something with Maven and something with YAML";
13
}
14
15
@Override
16
protected List<SourceFile> visit(List<SourceFile> before, ExecutionContext ctx) {
17
boolean pomConditionMet = false;
18
for (SourceFile sourceFile : before) {
19
if(sourceFile instanceof Maven) {
20
Maven m = (Maven) sourceFile;
21
// pomConditionMet = ...
22
}
23
}
24
25
return ListUtils.map(before, sourceFile -> (SourceFile) new YamlVisitor<Integer>() {
26
// whatever your YAML visitor does can now respond to pomConditionMet
27
}.visitNonNull(sourceFile, 0));
28
}
29
}
Copied!
To write a unit test that tests multiple source file types, use their respective parsers:
1
package org.openrewrite
2
3
import org.assertj.core.api.Assertions.assertThat
4
import org.junit.jupiter.api.Test
5
import org.openrewrite.maven.MavenParser
6
import org.openrewrite.yaml.YamlParser
7
8
class MavenYamlTest {
9
10
@Test
11
fun mavenYaml() {
12
val sources =
13
MavenParser.builder().build().parse(
14
"""
15
<project>
16
<groupId>org.openrewrite</groupId>
17
<artifactId>test</artifactId>
18
<version>0.1.0</version>
19
</project>
20
"""
21
).plus(
22
YamlParser().parse("""
23
key: value
24
""")
25
)
26
27
val results = MavenYaml().run(sources)
28
assertThat(results.map { it.after!!.printAll() }).containsExactly(
29
"""
30
key: changedValue
31
""".trimIndent()
32
)
33
}
34
}
Copied!
Export as PDF
Copy link