Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: don't apply error prone patches for disabled checks #793

Merged
merged 10 commits into from
Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
linkType = BugPattern.LinkType.CUSTOM,
severity = BugPattern.SeverityLevel.WARNING,
summary = "Throw SafeLoggable exceptions to ensure the exception message will not be redacted")
@SuppressWarnings("PreferSafeLoggableExceptions")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was undeterministically flaking compilation locally from gradle.. :(

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should disable the check on the whole project

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is already off, the baseline plugin itself turns it off for projects applying java-gradle-plugin.. I verified this with a snippet like so:

tasks.withType(JavaCompile) {
    println "${it.path}: ${options.errorprone.checks['PreferSafeLoggableExceptions']}"
}

and they are all OFF, however it doesn't seem to always take effect somehow

public final class PreferSafeLoggableExceptions extends BugChecker implements BugChecker.NewClassTreeMatcher {

private static final long serialVersionUID = 1L;
Expand Down
6 changes: 6 additions & 0 deletions changelog/@unreleased/pr-793.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
type: fix
fix:
description: Stop applying error prone patches for checks that have been turned
off.
links:
- https://github.com/palantir/gradle-baseline/pull/793
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@
import java.io.File;
import java.util.AbstractList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.ltgt.gradle.errorprone.CheckSeverity;
import net.ltgt.gradle.errorprone.ErrorProneOptions;
import net.ltgt.gradle.errorprone.ErrorPronePlugin;
Expand All @@ -36,13 +38,16 @@
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.RegularFile;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.plugins.ExtensionAware;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.javadoc.Javadoc;
import org.gradle.api.tasks.testing.Test;

public final class BaselineErrorProne implements Plugin<Project> {
private static final Logger log = Logging.getLogger(BaselineErrorProne.class);

public static final String REFASTER_CONFIGURATION = "refaster";
public static final String EXTENSION_NAME = "baselineErrorProne";
Expand All @@ -51,6 +56,7 @@ public final class BaselineErrorProne implements Plugin<Project> {
private static final String PROP_ERROR_PRONE_APPLY = "errorProneApply";
private static final String PROP_REFASTER_APPLY = "refasterApply";

@SuppressWarnings("UnstableApiUsage")
@Override
public void apply(Project project) {
project.getPluginManager().withPlugin("java", plugin -> {
Expand Down Expand Up @@ -132,10 +138,25 @@ public void apply(Project project) {
// TODO(gatesn): Is there a way to discover error-prone checks?
// Maybe service-load from a ClassLoader configured with annotation processor path?
// https://github.com/google/error-prone/pull/947
errorProneOptions.getErrorproneArgumentProviders().add(() -> ImmutableList.of(
"-XepPatchChecks:" + Joiner.on(',')
.join(errorProneExtension.getPatchChecks().get()),
"-XepPatchLocation:IN_PLACE"));
errorProneOptions.getErrorproneArgumentProviders().add(() -> {
// Don't apply checks that have been explicitly disabled
Stream<String> errorProneChecks = errorProneExtension
.getPatchChecks()
.get()
.stream()
.filter(check -> {
if (checkExplicitlyDisabled(errorProneOptions, check)) {
log.warn("Task {}: not applying errorprone check {} because it "
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this log line seems a little overkill

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alright, can make it info

+ "has severity OFF in errorProneOptions",
javaCompile.getPath(), check);
return false;
}
return true;
});
return ImmutableList.of(
"-XepPatchChecks:" + Joiner.on(',').join(errorProneChecks.iterator()),
"-XepPatchLocation:IN_PLACE");
});
}
}
});
Expand Down Expand Up @@ -208,6 +229,12 @@ private boolean isErrorProneRefactoring(Project project) {
return project.hasProperty(PROP_ERROR_PRONE_APPLY);
}

private static boolean checkExplicitlyDisabled(ErrorProneOptions errorProneOptions, String check) {
Map<String, CheckSeverity> checks = errorProneOptions.getChecks();
return checks.get(check) == CheckSeverity.OFF
|| errorProneOptions.getErrorproneArgs().contains(String.format("-Xep:%s:OFF", check));
}

private static final class LazyConfigurationList extends AbstractList<File> {
private final FileCollection files;
private List<File> fileList;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package com.palantir.baseline

import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome
import spock.lang.Unroll

/**
* This test depends on ./gradlew :baseline-error-prone:publishToMavenLocal
Expand Down Expand Up @@ -128,4 +129,50 @@ class BaselineErrorProneIntegrationTest extends AbstractPluginTest {
}
'''.stripIndent()
}

enum CheckConfigurationMethod { ARG, DSL }

@Unroll
def 'compileJava does not apply patches for error-prone checks that were turned OFF via #checkConfigurationMethod'() {
def checkName = "Slf4jLogsafeArgs"
def turnOffCheck = [
(CheckConfigurationMethod.ARG): "options.errorprone.errorproneArgs += ['-Xep:$checkName:OFF']",
(CheckConfigurationMethod.DSL): """
options.errorprone {
check '$checkName', net.ltgt.gradle.errorprone.CheckSeverity.OFF
}
""".stripIndent(),
]

buildFile << standardBuildFile
buildFile << """
tasks.withType(JavaCompile) {
${turnOffCheck[checkConfigurationMethod]}
}
dependencies {
implementation 'org.slf4j:slf4j-api:1.7.25'
}
""".stripIndent()

def correctJavaFile = '''
package test;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
public class Test {
void test() {
Logger log = LoggerFactory.getLogger("foo");
log.info("Hi there {}", "non safe arg");
}
}
'''.stripIndent()
file('src/main/java/test/Test.java') << correctJavaFile

expect:
BuildResult result = with('compileJava', '-PerrorProneApply').build()
result.task(":compileJava").outcome == TaskOutcome.SUCCESS
file('src/main/java/test/Test.java').text == correctJavaFile

where:
checkConfigurationMethod << CheckConfigurationMethod.values()
}
}