Skip to content

Commit

Permalink
Clear project.build.sourceEncoding after parsing sources (#735)
Browse files Browse the repository at this point in the history
* Clear `project.build.sourceEncoding` after parsing sources

* Apply suggestions from code review

* Only set Charset on JavaParser.Builder as discussed

* Also parse charset from plugin

* Check plugin first as that appears to allow override
  • Loading branch information
timtebeek committed Feb 20, 2024
1 parent a3cf901 commit a8dae80
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/main/java/org/openrewrite/maven/MavenMojoProjectParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
import org.openrewrite.maven.utilities.MavenWrapper;
import org.openrewrite.style.NamedStyles;
import org.openrewrite.tree.ParseError;
import org.openrewrite.tree.ParsingExecutionContextView;
import org.openrewrite.xml.tree.Xml;

import java.io.File;
Expand Down Expand Up @@ -169,13 +168,10 @@ public Stream<SourceFile> listSourceFiles(MavenProject mavenProject, @Nullable X
alreadyParsed.add(baseDir.resolve(maven.getSourcePath()));
}

Object mavenSourceEncoding = mavenProject.getProperties().get("project.build.sourceEncoding");
if (mavenSourceEncoding != null) {
ParsingExecutionContextView.view(ctx).setCharset(Charset.forName(mavenSourceEncoding.toString()));
}
JavaParser.Builder<? extends JavaParser, ?> javaParserBuilder = JavaParser.fromJavaVersion()
.styles(styles)
.logCompilationWarningsAndErrors(false);
getCharset(mavenProject).ifPresent(javaParserBuilder::charset);

// todo, add styles from autoDetect
KotlinParser.Builder kotlinParserBuilder = KotlinParser.builder();
Expand Down Expand Up @@ -222,6 +218,24 @@ public Stream<SourceFile> listSourceFiles(MavenProject mavenProject, @Nullable X
return sourceFiles.map(this::logParseErrors);
}

private static Optional<Charset> getCharset(MavenProject mavenProject) {
String compilerPluginKey = "org.apache.maven.plugins:maven-compiler-plugin";
Plugin plugin = Optional.ofNullable(mavenProject.getPlugin(compilerPluginKey))
.orElseGet(() -> mavenProject.getPluginManagement().getPluginsAsMap().get(compilerPluginKey));
if (plugin != null && plugin.getConfiguration() instanceof Xpp3Dom) {
Xpp3Dom encoding = ((Xpp3Dom) plugin.getConfiguration()).getChild("encoding");
if (encoding != null && StringUtils.isNotEmpty(encoding.getValue())) {
return Optional.of(Charset.forName(encoding.getValue()));
}
}

Object mavenSourceEncoding = mavenProject.getProperties().get("project.build.sourceEncoding");
if (mavenSourceEncoding != null) {
return Optional.of(Charset.forName(mavenSourceEncoding.toString()));
}
return Optional.empty();
}

private SourceFile logParseErrors(SourceFile source) {
if (source instanceof ParseError) {
if (firstWarningLogged.compareAndSet(false, true)) {
Expand Down

0 comments on commit a8dae80

Please sign in to comment.