Skip to content

Commit

Permalink
Fix hitherto untested moving of files as part of refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
sambsnyd committed Feb 19, 2021
1 parent ad3029c commit dff1b67
Show file tree
Hide file tree
Showing 8 changed files with 163 additions and 88 deletions.
5 changes: 2 additions & 3 deletions plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ val plugin: Configuration by configurations.creating
configurations.getByName("compileOnly").extendsFrom(plugin)

// Fixed version numbers because com.gradle.plugin-publish will publish poms with requested rather than resolved versions
// TODO: Update these to point to an 7.0.0-rc3 or the 7.0.0 GA once available
val rewriteVersion = "7.0.0-SNAPSHOT"
val rewriteVersion = "7.0.0-rc.5"
val prometheusVersion = "1.3.0"
val nettyVersion = "1.1.0"
dependencies {
Expand All @@ -75,7 +74,7 @@ dependencies {
plugin("io.rsocket:rsocket-transport-netty:$nettyVersion")

implementation("org.openrewrite:rewrite-java-11:$rewriteVersion")
implementation("org.openrewrite:rewrite-java-8:6.2.0-SNAPSHOT")
implementation("org.openrewrite:rewrite-java-8:$rewriteVersion")
implementation("org.openrewrite:rewrite-xml:$rewriteVersion")
implementation("org.openrewrite:rewrite-maven:$rewriteVersion")
implementation("org.openrewrite:rewrite-properties:$rewriteVersion")
Expand Down
153 changes: 101 additions & 52 deletions plugin/src/main/java/org/openrewrite/gradle/AbstractRewriteTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.SourceSet;
import org.openrewrite.ExecutionContext;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.Parser;
import org.openrewrite.Recipe;
import org.openrewrite.properties.PropertiesParser;
import org.openrewrite.style.NamedStyles;
Expand All @@ -39,17 +42,18 @@
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

public abstract class AbstractRewriteTask extends DefaultTask implements RewriteTask {

private String metricsUri;
private String metricsUsername;
private String metricsPassword;
@SuppressWarnings("FieldCanBeLocal")
private MeterRegistry registry;

private final SourceSet sourceSet;
Expand Down Expand Up @@ -97,95 +101,132 @@ public FileCollection getDependencies() {
}

protected Environment environment() {
Environment.Builder env = Environment.builder()
Map<Object, Object> gradleProps = getProject().getProperties().entrySet().stream()
.filter(entry -> entry.getKey() != null && entry.getValue() != null)
.collect(toMap(
Map.Entry::getKey,
Map.Entry::getValue));

Properties properties = new Properties();
properties.putAll(gradleProps);

Environment.Builder env = Environment.builder(properties)
.scanClasspath(
Stream.concat(
getDependencies().getFiles().stream(),
getJavaSources().getFiles().stream()
getDependencies().getFiles().stream(),
getJavaSources().getFiles().stream()
)
.map(File::toPath)
.collect(Collectors.toList())
.collect(toList())
)
.scanUserHome();

File rewriteConfig = extension.getConfigFile();
if (rewriteConfig != null && rewriteConfig.exists()) {
if (rewriteConfig.exists()) {
try (FileInputStream is = new FileInputStream(rewriteConfig)) {
Map<Object, Object> gradleProps = getProject().getProperties().entrySet().stream()
.filter(entry -> entry.getKey() != null && entry.getValue() != null)
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue));
Properties props = new Properties();
props.putAll(gradleProps);

YamlResourceLoader resourceLoader = new YamlResourceLoader(is, rewriteConfig.toURI(), props);
YamlResourceLoader resourceLoader = new YamlResourceLoader(is, rewriteConfig.toURI(), properties);
env.load(resourceLoader);
} catch (IOException e) {
throw new RuntimeException("Unable to load rewrite configuration", e);
}
} else if(extension.getConfigFileSetDeliberately()) {
} else if (extension.getConfigFileSetDeliberately()) {
getLog().warn("Rewrite configuration file " + rewriteConfig + " does not exist." +
"Supplied path: " + rewriteConfig + " configured for project " + getProject().getPath() + " does not exist");
}

return env.build();
}

protected ExecutionContext executionContext() {
return new InMemoryExecutionContext(t -> getLog().warn(t.getMessage(), t));
}

protected Parser.Listener listener() {
return new Parser.Listener() {
@Override
public void onError(String message) {
getLog().error(message);
}

@Override
public void onError(String message, Throwable t) {
getLog().error(message, t);
}
};
}

protected ResultsContainer listResults() {
try (MeterRegistryProvider meterRegistryProvider = new MeterRegistryProvider(getLog(), metricsUri, metricsUsername, metricsPassword)) {
MeterRegistry meterRegistry = meterRegistryProvider.registry();

Path baseDir = getProject().getRootProject().getProjectDir().toPath();

Environment env = environment();
Set<String> recipes = getActiveRecipes();
if (recipes == null || recipes.isEmpty()) {
Set<String> activeRecipes = getActiveRecipes();
if (activeRecipes.isEmpty()) {
return new ResultsContainer(baseDir, emptyList());
}
List<NamedStyles> styles = env.activateStyles(getActiveStyles());
Recipe recipe = env.activateRecipes(recipes);
Recipe recipe = env.activateRecipes(activeRecipes);

List<SourceFile> sourceFiles = new ArrayList<>();
List<Path> sourcePaths = getJavaSources().getFiles().stream()
.filter(it -> it.isFile() && it.getName().endsWith(".java"))
.map(File::toPath)
.map(AbstractRewriteTask::toRealPath)
.collect(toList());
List<Path> dependencyPaths = getDependencies().getFiles().stream()
.map(File::toPath)
.map(AbstractRewriteTask::toRealPath)
.collect(toList());

sourceFiles.addAll(JavaParser.fromJavaVersion()
.styles(styles)
.classpath(dependencyPaths)
.logCompilationWarningsAndErrors(false)
.build()
.parse(sourcePaths, baseDir)
ExecutionContext ctx = executionContext();
Parser.Listener listener = listener();

sourceFiles.addAll(
JavaParser.fromJavaVersion()
.styles(styles)
.classpath(dependencyPaths)
.logCompilationWarningsAndErrors(false)
.build()
.parse(sourcePaths, baseDir, ctx)
);

sourceFiles.addAll(new YamlParser().parse(
getResources().getFiles().stream()
.filter(it -> it.isFile() && it.getName().endsWith(".yml") || it.getName().endsWith(".yaml"))
.map(File::toPath)
.collect(toList()),
baseDir
));

sourceFiles.addAll(new PropertiesParser().parse(
getResources().getFiles().stream()
.filter(it -> it.isFile() && it.getName().endsWith(".properties"))
.map(File::toPath)
.collect(toList()),
baseDir
));

sourceFiles.addAll(new XmlParser().parse(
getResources().getFiles().stream()
.filter(it -> it.isFile() && it.getName().endsWith(".xml"))
.map(File::toPath)
.collect(toList()),
baseDir
));
sourceFiles.addAll(
YamlParser.builder()
.doOnParse(listener)
.build()
.parse(getResources().getFiles().stream()
.filter(it -> it.isFile() && it.getName().endsWith(".yml") || it.getName().endsWith(".yaml"))
.map(File::toPath)
.collect(toList()),
baseDir,
ctx
));

sourceFiles.addAll(
PropertiesParser.builder()
.doOnParse(listener)
.build()
.parse(
getResources().getFiles().stream()
.filter(it -> it.isFile() && it.getName().endsWith(".properties"))
.map(File::toPath)
.collect(toList()),
baseDir,
ctx
));

sourceFiles.addAll(
XmlParser.builder()
.doOnParse(listener)
.build().parse(
getResources().getFiles().stream()
.filter(it -> it.isFile() && it.getName().endsWith(".xml"))
.map(File::toPath)
.collect(toList()),
baseDir,
ctx
));

List<Result> results = recipe.run(sourceFiles);

Expand Down Expand Up @@ -230,9 +271,17 @@ public boolean isNotEmpty() {
}
}

protected void logVisitorsThatMadeChanges(Result result) {
for (String visitor : result.getRecipesThatMadeChanges()) {
getLog().warn(" " + visitor);
protected void logRecipesThatMadeChanges(Result result) {
for (Recipe recipe : result.getRecipesThatMadeChanges()) {
getLog().warn(" " + recipe.getName());
}
}

private static Path toRealPath(Path path) {
try {
return path.toRealPath();
} catch (IOException e) {
return path;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public void run() {
log.quiet("\t" + activeRecipe);
}

log.quiet("\nRecipes:");
log.quiet("Recipes:");
for(Recipe recipe : recipesByName) {
log.quiet("\tname: " + recipe.getName());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class RewriteExtension extends CodeQualityExtension {
private final List<String> activeRecipes = new ArrayList<>();
private final List<String> activeStyles = new ArrayList<>();
private boolean configFileSetDeliberately = false;
private Project project;
private final Project project;
private File configFile;
private String metricsUri = magicalMetricsLogString;

Expand Down
19 changes: 13 additions & 6 deletions plugin/src/main/java/org/openrewrite/gradle/RewriteFixTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@

import javax.inject.Inject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static java.nio.file.StandardOpenOption.CREATE;

public class RewriteFixTask extends AbstractRewriteTask {
private static final Logger log = Logging.getLogger(RewriteFixTask.class);

Expand All @@ -52,29 +55,29 @@ public void run() {
getLog().warn("Generated new file " +
result.getAfter().getSourcePath() +
" by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}
for(Result result : results.deleted) {
assert result.getBefore() != null;
getLog().warn("Deleted file " +
result.getBefore().getSourcePath() +
" by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}
for(Result result : results.moved) {
assert result.getAfter() != null;
assert result.getBefore() != null;
getLog().warn("File has been moved from " +
result.getBefore().getSourcePath() + " to " +
result.getAfter().getSourcePath() + " by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}
for(Result result : results.refactoredInPlace) {
assert result.getBefore() != null;
getLog().warn("Changes have been made to " +
result.getBefore().getSourcePath() +
" by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}

getLog().warn("Please review and commit the results.");
Expand Down Expand Up @@ -104,8 +107,12 @@ public void run() {
throw new IOException("Unable to delete file " + originalLocation.toAbsolutePath());
}
assert result.getAfter() != null;
try (BufferedWriter sourceFileWriter = Files.newBufferedWriter(
results.getProjectRoot().resolve(result.getAfter().getSourcePath()))) {
// Ensure directories exist in case something was moved into a hitherto non-existent package
Path afterLocation = results.getProjectRoot().resolve(result.getAfter().getSourcePath());
File parentDir = afterLocation.toFile().getParentFile();
//noinspection ResultOfMethodCallIgnored
parentDir.mkdirs();
try (BufferedWriter sourceFileWriter = Files.newBufferedWriter(afterLocation)) {
sourceFileWriter.write(result.getAfter().print());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,29 +48,29 @@ public void run() {
getLog().warn("Applying fixes would generate new file " +
result.getAfter().getSourcePath() +
" by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}
for(Result result : results.deleted) {
assert result.getBefore() != null;
getLog().warn("Applying fixes would delete file " +
result.getBefore().getSourcePath() +
" by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}
for(Result result : results.moved) {
assert result.getBefore() != null;
assert result.getAfter() != null;
getLog().warn("Applying fixes would move file from " +
result.getBefore().getSourcePath() + " to " +
result.getAfter().getSourcePath() + " by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}
for(Result result : results.refactoredInPlace) {
assert result.getBefore() != null;
getLog().warn("Applying fixes would make results to " +
result.getBefore().getSourcePath() +
" by:");
logVisitorsThatMadeChanges(result);
logRecipesThatMadeChanges(result);
}
getLog().warn("Run 'gradle rewriteFix' to apply the fixes. Afterwards, review and commit the results.");
}
Expand Down
19 changes: 19 additions & 0 deletions plugin/src/main/java/org/openrewrite/gradle/package-info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* Copyright ${year} the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@NonNullApi
package org.openrewrite.gradle;

import org.openrewrite.internal.lang.NonNullApi;
Loading

0 comments on commit dff1b67

Please sign in to comment.