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

Clean up synthetic accessor method rot #2762

Merged
merged 5 commits into from
Dec 30, 2017
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,7 @@ docs/**/*

# Intellij
*.iml
*.ipr
*.iws
.idea/**
!.idea/codeStyleSettings.xml
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ buildscript {
dependencies {
classpath "com.android.tools.build:gradle:${ANDROID_GRADLE_VERSION}"
if (!hasProperty('DISABLE_ERROR_PRONE')) {
classpath "net.ltgt.gradle:gradle-errorprone-plugin:${ERROR_PRONE_VERSION}"
classpath "net.ltgt.gradle:gradle-errorprone-plugin:${ERROR_PRONE_PLUGIN_VERSION}"
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion checkstyle.xml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@

<!-- Allow common trailing comments used to describe suppressions -->
<module name="TrailingComment">
<property name="legalComment" value="Public API" />
<property name="legalComment" value="^Public API.?$|^NOPMD .*$" />
</module>

<!-- Checks for imports. -->
Expand Down
5 changes: 3 additions & 2 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ JSR_305_VERSION=3.0.2
AUTO_SERVICE_VERSION=1.0-rc3
JAVAPOET_VERSION=1.9.0

PMD_VERSION=5.4.0
PMD_VERSION=5.8.1
FINDBUGS_VERSION=3.0.0
ERROR_PRONE_VERSION=0.0.13
ERROR_PRONE_VERSION=2.1.4-SNAPSHOT
ERROR_PRONE_PLUGIN_VERSION=0.0.13

COMPILE_SDK_VERSION=26
TARGET_SDK_VERSION=26
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
Expand Down Expand Up @@ -95,6 +94,8 @@ public void setUp() {

@After
public void tearDown() {
// GC before delete() to release files on Windows (https://stackoverflow.com/a/4213208/253468)
System.gc();
if (file.exists() && !file.delete()) {
throw new RuntimeException("Failed to delete file");
}
Expand All @@ -120,8 +121,6 @@ public void testEncodeStrategy_withEncodeTransformationFalse_returnsSource() {
@Test
public void testEncode_withEncodeTransformationFalse_writesSourceDataToStream()
throws IOException {
// Most likely an instance of http://stackoverflow.com/q/991489/253468
assumeTrue(!System.getProperty("os.name").startsWith("Windows"));
options.set(ReEncodingGifResourceEncoder.ENCODE_TRANSFORMATION, false);
String expected = "testString";
byte[] data = expected.getBytes("UTF-8");
Expand All @@ -134,7 +133,6 @@ public void testEncode_withEncodeTransformationFalse_writesSourceDataToStream()
@Test
public void testEncode_WithEncodeTransformationFalse_whenOsThrows_returnsFalse()
throws IOException {

options.set(ReEncodingGifResourceEncoder.ENCODE_TRANSFORMATION, false);
byte[] data = "testString".getBytes("UTF-8");
when(gifDrawable.getBuffer()).thenReturn(ByteBuffer.wrap(data));
Expand Down Expand Up @@ -312,10 +310,7 @@ public void testRecyclesFrameResourceAfterWritingIfFrameResourceIsNotTransformed
}

@Test
public void testWritesBytesDirectlyToDiskIfTransformationIsUnitTransformation()
throws IOException {
// Most likely an instance of http://stackoverflow.com/q/991489/253468
assumeTrue(!System.getProperty("os.name").startsWith("Windows"));
public void testWritesBytesDirectlyToDiskIfTransformationIsUnitTransformation() {
when(gifDrawable.getFrameTransformation()).thenReturn(UnitTransformation.<Bitmap>get());
String expected = "expected";
when(gifDrawable.getBuffer()).thenReturn(ByteBuffer.wrap(expected.getBytes()));
Expand Down
4 changes: 4 additions & 0 deletions library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ dependencies {
testImplementation "org.robolectric:robolectric:${ROBOLECTRIC_VERSION}"
testImplementation "com.squareup.okhttp3:mockwebserver:${MOCKWEBSERVER_VERSION}"
testImplementation "com.android.support:support-v4:${ANDROID_SUPPORT_VERSION}"

if (project.plugins.hasPlugin('net.ltgt.errorprone')) {
errorprone "com.google.errorprone:error_prone_core:${ERROR_PRONE_VERSION}"
}
}

android.testOptions.unitTests.all { Test testTask ->
Expand Down
52 changes: 31 additions & 21 deletions library/pmd-ruleset.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">

<description>This ruleset was created from PMD.rul</description>
<description>Check for flaws in Glide's codebase.</description>

<rule ref="rulesets/java/basic.xml">
<exclude name="AvoidBranchingStatementAsLastInLoop"/>
</rule>
<rule ref="rulesets/java/braces.xml"/>
<rule ref="rulesets/java/strings.xml">
<!-- TODO: This warns about annotations, apparently fixed in a later version. -->
<exclude name="AvoidDuplicateLiterals"/>
<rule ref="rulesets/java/strings.xml"/>
<rule ref="rulesets/java/strings.xml/AvoidDuplicateLiterals">
<properties>
<property name="skipAnnotations" value="true" />
</properties>
</rule>
<rule ref="rulesets/java/unusedcode.xml"/>

Expand All @@ -28,31 +30,39 @@
<exclude name="GodClass"/>
</rule>

<rule ref="rulesets/java/design.xml/AccessorMethodGeneration"
message="Avoid autogenerated methods to access private fields and methods of inner / outer classes.
Use @Synthetic to flag members made more visible than necessary to prevent accessors.">
<properties>
<!-- Ignore references to `private static final * * = <literal>`
Suppress via XPath: current node (access that generates the accessor) is .
Check if there exists a FieldDeclaration (private static final)
which has a VariableInitializer with a Literal
and the name (@Image) of the declaration is the same as the accessed member.
TODO calculated constants are false positive https://github.com/pmd/pmd/issues/808
-->
<property name="violationSuppressXPath" value="
.[@Image =
//FieldDeclaration[@Private = 'true' and @Static='true' and @Final='true']
/VariableDeclarator[
VariableInitializer/Expression/PrimaryExpression[not(PrimarySuffix)]/PrimaryPrefix/Literal
]/VariableDeclaratorId/@Image
]" />
</properties>
</rule>

<rule ref="rulesets/java/empty.xml/EmptyCatchBlock" message="Commented blocks are ok">
<properties>
<property name="allowCommentedBlocks" value="true"/>
</properties>
</rule>


<!--Overrides default check to avoid violation when @Synthetic annotation is present-->
<rule ref="rulesets/java/design.xml/UncommentedEmptyConstructor"
message="Document empty constructor">

<!-- Configures check to avoid violation when @Synthetic annotation is present. -->
<rule ref="rulesets/java/design.xml/UncommentedEmptyConstructor">
<properties>
<property name="xpath">
<value>
<![CDATA[
//ConstructorDeclaration[@Private='false'][count(BlockStatement) = 0 and
($ignoreExplicitConstructorInvocation = 'true' or not(ExplicitConstructorInvocation)) and @containsComment = 'false'
and not(../Annotation/MarkerAnnotation/Name[@Image='Synthetic'])]
]]>
</value>
</property>

<property name="violationSuppressXPath"
value="../Annotation/MarkerAnnotation/Name[@Image='Synthetic']" />
</properties>

</rule>


</ruleset>
6 changes: 5 additions & 1 deletion library/src/main/java/com/bumptech/glide/RequestBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.support.annotation.RestrictTo;
import android.support.annotation.RestrictTo.Scope;
import android.widget.ImageView;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
Expand All @@ -30,6 +32,7 @@
import com.bumptech.glide.request.target.ViewTarget;
import com.bumptech.glide.signature.ApplicationVersionSignature;
import com.bumptech.glide.util.Preconditions;
import com.bumptech.glide.util.Synthetic;
import com.bumptech.glide.util.Util;
import java.io.File;
import java.net.URL;
Expand Down Expand Up @@ -571,8 +574,9 @@ public <Y extends Target<TranscodeType>> Y into(@NonNull Y target) {
return into(target, /*targetListener=*/ null);
}

@RestrictTo(Scope.LIBRARY)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm ok not using this for non-public methods. I assume anything that's non-public can be broken and even some of the public APIs we have are breakable (those really should be marked with @RestrictTo or some equivalent.

Fine to keep it, just as a note for the future (or a discussion point).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Lot of negation there :)
You're right: default methods don't need this, if someone uses "internal" (name/keyword for default visibility in other languages) API, they can fix it if we break something. protected on public classes may need this, and public methods that are only public because of packages, and not because it's public API also need this. I'll remove from default ones.

@NonNull
private <Y extends Target<TranscodeType>> Y into(
@Synthetic <Y extends Target<TranscodeType>> Y into(
@NonNull Y target,
@Nullable RequestListener<TranscodeType> targetListener) {
return into(target, targetListener, getMutableOptions());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ EngineResource<?> get(Key key) {
return active;
}

private void cleanupActiveReference(@NonNull ResourceWeakReference ref) {
@SuppressWarnings("WeakerAccess")
@Synthetic void cleanupActiveReference(@NonNull ResourceWeakReference ref) {
Util.assertMainThread();
activeEngineResources.remove(ref.key);

Expand All @@ -112,29 +113,33 @@ private ReferenceQueue<EngineResource<?>> getReferenceQueue() {
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
ResourceWeakReference ref;
while (!isShutdown) {
try {
ref = (ResourceWeakReference) resourceReferenceQueue.remove();
mainHandler.obtainMessage(MSG_CLEAN_REF, ref).sendToTarget();

// This section for testing only.
DequeuedResourceCallback current = cb;
if (current != null) {
current.onResourceDequeued();
}
// End for testing only.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
cleanReferenceQueue();
}
}, "glide-active-resources");
cleanReferenceQueueThread.start();
}
return resourceReferenceQueue;
}

@SuppressWarnings("WeakerAccess")
@Synthetic void cleanReferenceQueue() {
while (!isShutdown) {
try {
ResourceWeakReference ref = (ResourceWeakReference) resourceReferenceQueue.remove();
mainHandler.obtainMessage(MSG_CLEAN_REF, ref).sendToTarget();

// This section for testing only.
DequeuedResourceCallback current = cb;
if (current != null) {
current.onResourceDequeued();
}
// End for testing only.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

@VisibleForTesting
void setDequeuedResourceCallback(DequeuedResourceCallback cb) {
this.cb = cb;
Expand Down
Loading