Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/858-incorporate-new-parser-into-…
Browse files Browse the repository at this point in the history
…core' into 858-incorporate-new-parser-into-core

# Conflicts:
#	applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplyShellCommand.java
#	components/sbm-core/src/main/java/org/springframework/sbm/SbmCoreConfig.java
#	components/sbm-core/src/main/java/org/springframework/sbm/build/impl/OpenRewriteMavenBuildFile.java
#	components/sbm-core/src/main/java/org/springframework/sbm/build/migration/actions/AddMinimalPomXml.java
#	components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependenciesChangedEventHandler.java
#	components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteMember.java
#	components/sbm-core/src/main/java/org/springframework/sbm/properties/api/PropertiesSource.java
#	components/sbm-core/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java
#	components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/AddDependencyTest.java
#	components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/OpenRewriteMavenBuildFileTest.java
#	components/sbm-core/src/test/java/org/springframework/sbm/project/parser/MavenProjectParserTest.java
#	components/sbm-openrewrite/src/main/java/org/springframework/sbm/support/openrewrite/java/AddAnnotationVisitor.java
#	pom.xml
#	sbm-support-rewrite/pom.xml
#	sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/ScopeConfiguration.java
#	sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java
#	sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/ProjectScanner.java
#	sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteParserConfiguration.java
#	sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteProjectParser.java
#	sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/SourceFileParser.java
#	sbm-support-rewrite/src/main/java/org/springframework/sbm/support/openrewrite/GenericOpenRewriteRecipe.java
#	sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/MavenPomCacheTest.java
#	sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/ParserPropertiesTest.java
#	sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserIntegrationTest.java
#	sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserTest.java
#	sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserIntegrationTest.java
#	sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserTest.java
  • Loading branch information
fabapp2 committed Sep 14, 2023
2 parents a1d14b5 + 5e9fb24 commit 54de4bc
Show file tree
Hide file tree
Showing 12 changed files with 45 additions and 103 deletions.
4 changes: 4 additions & 0 deletions components/sbm-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@

<artifactId>sbm-core</artifactId>

<properties>
<java.version>17</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.sbm</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -682,13 +682,6 @@ public List<Path> getTestResourceFolders() {
return List.of(getAbsolutePath().getParent().resolve(RESOURCE_TEST_FOLDER));
}

public List<Path> getClasspath() {
List<Path> classpath = new ArrayList<>();
classpath.add(getSourceFile().getSourcePath().toAbsolutePath().getParent().resolve("target/classes"));
classpath.addAll(getResolvedDependenciesPaths());
return classpath;
}

@Override
public List<Path> getResolvedDependenciesPaths() {
List<Path> dependenciesPaths = getResolvedDependenciesMap().values().stream().flatMap(Set::stream).toList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,6 @@ public class AddMinimalPomXml extends AbstractAction {
@JsonIgnore
private ExecutionContext executionContext;

@Autowired
@JsonIgnore
private RewriteMavenArtifactDownloader rewriteMavenArtifactDownloader;

@Autowired
@JsonIgnore
private RewriteMavenArtifactDownloader artifactDownloader;
Expand Down Expand Up @@ -90,7 +86,7 @@ public void apply(ProjectContext context) {
context.getProjectRootDirectory(),
maven, getEventPublisher(), executionContext,
mavenBuildFileRefactoringFactory.createRefactoring(),
rewriteMavenArtifactDownloader
artifactDownloader
);
context.getProjectResources().add(rewriteMavenBuildFile);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public class ControlledInstantiationOfExecutionContextTest {
)
.andShould(notBe(classWithPermissionToCreateExecutionContext).and(notBe(SbmCoreConfig.class)))
.andShould()
.notBe(SbmCoreConfig.class)
.notBe(classWithPermissionToCreateExecutionContext)
.andShould()
.notBe(RewriteExecutionContext.class)
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ void addDependencyShouldPublishEvent() {
)
.withJavaSource("src/main/java",
"""
import jakarta.validation.constraints.Email;
import javax.validation.constraints.Email;
public class Cat {
@Email
private String email;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public class AddAnnotationVisitor extends JavaIsoVisitor<ExecutionContext> {
private final String snippet;
private final String[] imports;
private final Supplier<JavaParser.Builder> javaParserSupplier;
// ugly, just because UUID of elemnts stay same now and can't be used as criteria leading to multiple visits of the same .
private boolean targetVisited;

public AddAnnotationVisitor(JavaParser.Builder javaParserSupplier, J target, String snippet, String annotationImport, String... otherImports) {
this(() -> javaParserSupplier, target, snippet, annotationImport, otherImports);
Expand All @@ -50,39 +52,42 @@ public AddAnnotationVisitor(Supplier<JavaParser.Builder> javaParserSupplier, J t

public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext p) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, p);
if (target.getId().equals(cd.getId())) {
if (target.getId().equals(cd.getId()) && !targetVisited) {
JavaTemplate template = JavaTemplate.builder(snippet)
.imports(imports)
.build();
Stream.of(imports).forEach(i -> maybeAddImport(i, null, false));
JavaCoordinates coordinates = cd.getCoordinates().addAnnotation((o1, o2) -> 0);
cd = template.apply(getCursor(), coordinates);
targetVisited = true;
}
return cd;
}


public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl, ExecutionContext p) {
J.MethodDeclaration md = super.visitMethodDeclaration(methodDecl, p);
if (target.getId().equals(md.getId())) {
if (target.getId().equals(md.getId()) && !targetVisited) {
JavaTemplate template = JavaTemplate.builder(snippet)
.imports(imports)
.build();
Stream.of(imports).forEach(i -> {
maybeAddImport(i, null, false);
});
md = template.apply(getCursor(), md.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
targetVisited = true;
}
return md;
}

@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext p) {
J.VariableDeclarations vd = super.visitVariableDeclarations(multiVariable, p);
if (target.getId().equals(vd.getId())) {
JavaTemplate template = JavaTemplate.builder(snippet).javaParser(javaParserSupplier.get()).imports(imports).build();
if (target.getId().equals(vd.getId()) && !targetVisited) {
JavaTemplate template = JavaTemplate.builder(snippet).imports(imports).build();
Stream.of(imports).forEach(i -> maybeAddImport(i, null, false));
vd = template.apply(getCursor(), vd.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
targetVisited = true;
}
return vd;
}
Expand Down
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,11 @@
<artifactId>sbm-support-rewrite</artifactId>
<version>${sbm-support-rewrite.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.experimental</groupId>
<artifactId>sbm-support-rewrite</artifactId>
<version>${sbm-support-rewrite.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${jar.name}</finalName>
Expand Down
5 changes: 2 additions & 3 deletions sbm-support-rewrite/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>3.1.3</spring-boot.version>
<rewrite.version>8.4.2</rewrite.version>
<rewrite-spring.version>5.0.5</rewrite-spring.version>
<rewrite.version>8.5.0</rewrite.version>
<sbm.version>0.15.0-SNAPSHOT</sbm.version>
<rewrite-maven-plugin.version>5.3.2</rewrite-maven-plugin.version>
<maven.version>3.9.1</maven.version>
Expand Down Expand Up @@ -330,7 +329,7 @@
<configuration>
<properties>
<owner>the original author or authors.</owner>
<email />
<email/>
<year>2023</year>
</properties>
<licenseSets>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@
*/
@Slf4j
@RequiredArgsConstructor
public
class ProjectScanner {
public class ProjectScanner {
private final ResourceLoader resourceLoader;
private final ParserProperties parserProperties;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.Parser;
import org.openrewrite.SourceFile;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.marker.JavaProject;
import org.openrewrite.java.marker.JavaSourceSet;
import org.openrewrite.java.marker.JavaVersion;
Expand All @@ -40,7 +38,9 @@
import org.openrewrite.marker.ci.GithubActionsBuildEnvironment;
import org.openrewrite.maven.MavenExecutionContextView;
import org.openrewrite.maven.MavenSettings;
import org.openrewrite.maven.cache.CompositeMavenPomCache;
import org.openrewrite.maven.cache.InMemoryMavenPomCache;
import org.openrewrite.maven.cache.LocalMavenArtifactCache;
import org.openrewrite.maven.cache.MavenArtifactCache;
import org.openrewrite.maven.cache.InMemoryMavenPomCache;
import org.openrewrite.maven.cache.LocalMavenArtifactCache;
import org.openrewrite.maven.cache.MavenArtifactCache;
Expand Down Expand Up @@ -98,7 +98,6 @@ class RewriteMavenProjectParserTest {
void beforeEach() {
beanFactory = mock(ConfigurableListableBeanFactory.class);
scanScope = mock(ScanScope.class);
ExecutionContext executionContext = new InMemoryExecutionContext(t -> {throw new RuntimeException(t);});
sut = new RewriteMavenProjectParser(
plexusContainer,
new RewriteParsingEventListenerAdapter(mock(ApplicationEventPublisher.class)),
Expand Down Expand Up @@ -418,8 +417,9 @@ private static void verifyExecutionContext(RewriteProjectParsingResult parsingRe
// 8
assertThat(
messages.get("org.openrewrite.maven.pomCache")
).isInstanceOf(CompositeMavenPomCache.class);
assertThat(MavenExecutionContextView.view(resultingExecutionContext).getPomCache()).isInstanceOf(CompositeMavenPomCache.class);
).isNull();
assertThat(MavenExecutionContextView.view(resultingExecutionContext).getPomCache()).isInstanceOf(InMemoryMavenPomCache.class);
// assertThat(MavenExecutionContextView.view(resultingExecutionContext).getPomCache()).isInstanceOf(CompositeMavenPomCache.class);

// 9
// FIXME: This fails sometimes when multiple tests are run together. The resolution time has been 0 and null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,20 @@
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.openrewrite.ExecutionContext;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.java.tree.J;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.event.EventListener;
import org.springframework.core.io.Resource;
import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration;
import org.springframework.sbm.parsers.events.FinishedParsingResourceEvent;
import org.springframework.sbm.parsers.events.StartedParsingProjectEvent;
import org.springframework.sbm.parsers.events.SuccessfullyParsedProjectEvent;
import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

Expand All @@ -51,72 +48,7 @@ public class RewriteProjectParserIntegrationTest {
ProjectScanner projectScanner;

@Autowired
ParserProperties parserProperties;

private static List<FinishedParsingResourceEvent> capturedEvents = new ArrayList<>();
private static StartedParsingProjectEvent startedParsingEvent;
private static SuccessfullyParsedProjectEvent finishedParsingEvent;

@Test
@DisplayName("Should publish parsing events")
@Disabled("FIXME https://github.com/spring-projects-experimental/spring-boot-migrator/issues/902")
void shouldPublishParsingEvents() {
// remove events recorded in other tests
capturedEvents.clear();

Path baseDir = Path.of("./testcode/maven-projects/multi-module-1");
parserProperties.setIgnoredPathPatterns(Set.of("**/target/**", "**/*.adoc"));
List<Resource> resources = projectScanner.scan(baseDir);
ExecutionContext ctx = new InMemoryExecutionContext(t -> {throw new RuntimeException(t);});

RewriteProjectParsingResult parsingResult = sut.parse(baseDir, resources, ctx);

assertThat(capturedEvents).hasSize(3);
assertThat(capturedEvents.get(0).sourceFile().getSourcePath().toString())
.isEqualTo("pom.xml");
// FIXME: Parsing order differs from RewriteMavenProjectParser but b should be parsed first as it has no dependencies
// Reported to OR the order gets lost in a Set in MavenMojoProjectParser
assertThat(capturedEvents.get(1).sourceFile().getSourcePath().toString())
.isEqualTo("module-b/pom.xml");
assertThat(capturedEvents.get(2).sourceFile().getSourcePath().toString())
.isEqualTo("module-a/pom.xml");

assertThat(startedParsingEvent).isNotNull();
assertThat(startedParsingEvent.resources()).isSameAs(resources);
assertThat(finishedParsingEvent).isNotNull();
assertThat(finishedParsingEvent.sourceFiles()).isSameAs(parsingResult.sourceFiles());
}

@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("testFailingProject")
// FIXME: Succeeds with RewriteMavenProjectParser
void testFailingProject() {
Path baseDir = Path.of("./testcode/maven-projects/failing");
RewriteProjectParsingResult parsingResult = sut.parse(baseDir);
assertThat(parsingResult.sourceFiles().get(1)).isInstanceOf(J.CompilationUnit.class);
J.CompilationUnit cu = (J.CompilationUnit) parsingResult.sourceFiles().get(1);
assertThat(cu.getTypesInUse().getTypesInUse().stream().map(t -> t.toString()).anyMatch(t -> t.equals("javax.validation.constraints.Min"))).isTrue();
}
@TestConfiguration
static class TestEventListener {


@EventListener(FinishedParsingResourceEvent.class)
public void onEvent(FinishedParsingResourceEvent event) {
capturedEvents.add(event);
}

@EventListener(StartedParsingProjectEvent.class)
public void onStartedParsingProjectEvent(StartedParsingProjectEvent event) {
startedParsingEvent = event;
}

@EventListener(SuccessfullyParsedProjectEvent.class)
public void onFinishedParsingProjectEvent(SuccessfullyParsedProjectEvent event) {
finishedParsingEvent = event;
}
}

RewriteMavenProjectParser mavenProjectParser;

@Test
@DisplayName("parseCheckstyle")
Expand All @@ -127,7 +59,6 @@ void parseCheckstyle() {
assertThat(parsingResult.sourceFiles().stream().map(sf -> sf.getSourcePath().toString()).toList()).contains("checkstyle/rules.xml");
assertThat(parsingResult.sourceFiles().stream().map(sf -> sf.getSourcePath().toString()).toList()).contains("checkstyle/suppressions.xml");
}

@Test
@DisplayName("parse4Modules")
void parse4Modules() {
Expand All @@ -140,8 +71,16 @@ void parse4Modules() {
assertThat(parsingResult.sourceFiles()).hasSize(4);
}

@Autowired
RewriteMavenProjectParser mavenProjectParser;
@Test
@DisplayName("testFailingProject")
// FIXME: Succeeds with RewriteMavenProjectParser
void testFailingProject() {
Path baseDir = Path.of("./testcode/maven-projects/failing");
RewriteProjectParsingResult parsingResult = sut.parse(baseDir);
assertThat(parsingResult.sourceFiles().get(1)).isInstanceOf(J.CompilationUnit.class);
J.CompilationUnit cu = (J.CompilationUnit) parsingResult.sourceFiles().get(1);
assertThat(cu.getTypesInUse().getTypesInUse().stream().map(t -> t.toString()).anyMatch(t -> t.equals("javax.validation.constraints.Min"))).isTrue();
}

@Test
@DisplayName("parseResources")
Expand All @@ -162,5 +101,4 @@ private Path getMavenProject(String s) {
return Path.of("./testcode/maven-projects/").resolve(s).toAbsolutePath().normalize();
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ public static void main(String[] args){
void parseSimpleMavenProject(@TempDir Path tempDir) {
Path basePath = tempDir;
ParserProperties parserProperties = new ParserProperties();
MavenModelReader mavenModelReader = new MavenModelReader();
MavenMojoProjectParserFactory mavenMojoProjectParserFactory = new MavenMojoProjectParserFactory(parserProperties);
MavenArtifactCache mavenArtifactCache = new LocalMavenArtifactCache(Paths.get(System.getProperty("user.home"), ".m2", "repository"));
@Nullable MavenSettings mavenSettings = null;
Expand Down Expand Up @@ -127,6 +128,8 @@ public void parsed(Parser.Input input, SourceFile sourceFile) {
}
);

// TODO: Provide Scanner with excludes
// TODO: Make RewriteProjectParser publish ApplicationEvents
List<Resource> resources = List.of(
new DummyResource(basePath.resolve("pom.xml"), pomXml),
new DummyResource(basePath.resolve("src/main/java/com/example/MyMain.java"), javaClass));
Expand Down

0 comments on commit 54de4bc

Please sign in to comment.