From a8dae8085828c167553f6af50b36b0beb4599661 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 20 Feb 2024 21:32:16 +0100 Subject: [PATCH] Clear `project.build.sourceEncoding` after parsing sources (#735) * 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 --- .../maven/MavenMojoProjectParser.java | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/openrewrite/maven/MavenMojoProjectParser.java b/src/main/java/org/openrewrite/maven/MavenMojoProjectParser.java index 8fc97e19..9ca8bdc2 100644 --- a/src/main/java/org/openrewrite/maven/MavenMojoProjectParser.java +++ b/src/main/java/org/openrewrite/maven/MavenMojoProjectParser.java @@ -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; @@ -169,13 +168,10 @@ public Stream 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 javaParserBuilder = JavaParser.fromJavaVersion() .styles(styles) .logCompilationWarningsAndErrors(false); + getCharset(mavenProject).ifPresent(javaParserBuilder::charset); // todo, add styles from autoDetect KotlinParser.Builder kotlinParserBuilder = KotlinParser.builder(); @@ -222,6 +218,24 @@ public Stream listSourceFiles(MavenProject mavenProject, @Nullable X return sourceFiles.map(this::logParseErrors); } + private static Optional 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)) {