[java] Fix #5067: CloseResource: False positive for FileSystems.getDefault()

This commit is contained in:
lukasgraef
2024-09-21 16:03:36 +02:00
parent 2c48dc0644
commit ddb1eb8dd8
2 changed files with 21 additions and 0 deletions

View File

@ -204,6 +204,7 @@ public class CloseResourceRule extends AbstractJavaRule {
.filter(this::isVariableNotSpecifiedInTryWithResource)
.filter(var -> isResourceTypeOrSubtype(var) || isNodeInstanceOfResourceType(getTypeOfVariable(var)))
.filterNot(var -> var.isAnnotationPresent("lombok.Cleanup"))
.filterNot(this::isDefaultFileSystem)
.toList();
for (ASTVariableId var : vars) {
@ -499,6 +500,12 @@ public class CloseResourceRule extends AbstractJavaRule {
return tryStatement == null || !isVariableSpecifiedInTryWithResource(varId, tryStatement);
}
private boolean isDefaultFileSystem(ASTVariableId varId) {
@Nullable
ASTExpression initializer = varId.getInitializer();
return initializer != null && initializer.getText().contentEquals("FileSystems.getDefault()");
}
private boolean isVariableSpecifiedInTryWithResource(ASTVariableId varId, ASTTryStatement tryWithResource) {
// skip own resources - these are definitively closed
if (tryWithResource.getResources().descendants(ASTVariableId.class).toList().contains(varId)) {

View File

@ -2044,6 +2044,20 @@ public class CastedParameter {
// doesn't need to be closed, it's still a paramter…
}
}
}
]]></code>
</test-code>
<test-code>
<description>#5067: FileSystems.getDefault() can't be closed </description>
<expected-problems>0</expected-problems>
<code><![CDATA[
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
public class DefaultFileSystemUsage {
public void useDefaultFS() {
FileSystem defaultFS = FileSystems.getDefault();
}
}
]]></code>
</test-code>