Skip to content

Commit 2882bfc

Browse files
authored
Removed unused handles in file-resource-leak (#648)
1 parent aebb18b commit 2882bfc

File tree

2 files changed

+29
-16
lines changed

2 files changed

+29
-16
lines changed

src/core_codemods/file_resource_leak.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -229,12 +229,16 @@ def _handle_block(
229229
)
230230

231231
# grab the index of the last statement with reference to the resource
232-
last_index = (
233-
self._find_last_index_with_access(
234-
named_targets, original_block, index
235-
)
236-
or index
232+
last_index = self._find_last_index_with_access(
233+
named_targets, original_block, index
237234
)
235+
236+
# No accesses, remove the statement
237+
if last_index is None:
238+
new_stmts[index] = cst.Pass()
239+
new_index_of_original_stmt[index] = -1
240+
continue
241+
238242
# check if the statement in the last_index is now included in some earlier with statement
239243
new_last_index = new_index_of_original_stmt[last_index]
240244

tests/codemods/test_file_resource_leak.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,26 @@ def test_simple(self, tmpdir):
1919
"""
2020
self.run_and_assert(tmpdir, input_code, expected)
2121

22+
def test_unused(self, tmpdir):
23+
input_code = """
24+
file = open('test.txt', 'r')
25+
"""
26+
expected = """
27+
"""
28+
self.run_and_assert(tmpdir, input_code, expected)
29+
30+
def test_unused_inside_block(self, tmpdir):
31+
input_code = """
32+
file = open('test.txt', 'r')
33+
file2 = open('test2.txt','r')
34+
file.read()
35+
"""
36+
expected = """
37+
with open('test.txt', 'r') as file:
38+
file.read()
39+
"""
40+
self.run_and_assert(tmpdir, input_code, expected, num_changes=2)
41+
2242
def test_simple_annotated(self, tmpdir):
2343
input_code = """
2444
file: int = open('test.txt', 'r')
@@ -59,17 +79,6 @@ def foo():
5979
"""
6080
self.run_and_assert(tmpdir, input_code, expected, num_changes=4)
6181

62-
def test_just_open(self, tmpdir):
63-
# strange as this change may be, it still leaks if left untouched
64-
input_code = """
65-
file = open('test.txt', 'r')
66-
"""
67-
expected = """
68-
with open('test.txt', 'r') as file:
69-
pass
70-
"""
71-
self.run_and_assert(tmpdir, input_code, expected)
72-
7382
def test_multiple_assignments(self, tmpdir):
7483
input_code = """
7584
file = file2 = open('test.txt', 'r')

0 commit comments

Comments
 (0)