Skip to content

Commit f957c81

Browse files
committed
Handle more file open/close with "with"
1 parent d1996e0 commit f957c81

File tree

4 files changed

+10
-15
lines changed

4 files changed

+10
-15
lines changed

Diff for: gitdb/db/ref.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ def _update_dbs_from_ref_file(self):
4141
# try to get as many as possible, don't fail if some are unavailable
4242
ref_paths = list()
4343
try:
44-
ref_paths = [l.strip() for l in open(self._ref_file, 'r').readlines()]
44+
with open(self._ref_file, 'r') as f:
45+
ref_paths = [l.strip() for l in f]
4546
except (OSError, IOError):
4647
pass
4748
# END handle alternates

Diff for: gitdb/test/db/test_ref.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,9 @@ class TestReferenceDB(TestDBBase):
2121
def make_alt_file(self, alt_path, alt_list):
2222
"""Create an alternates file which contains the given alternates.
2323
The list can be empty"""
24-
alt_file = open(alt_path, "wb")
25-
for alt in alt_list:
26-
alt_file.write(alt.encode("utf-8") + "\n".encode("ascii"))
27-
alt_file.close()
24+
with open(alt_path, "wb") as alt_file:
25+
for alt in alt_list:
26+
alt_file.write(alt.encode("utf-8") + "\n".encode("ascii"))
2827

2928
@with_rw_directory
3029
def test_writing(self, path):

Diff for: gitdb/test/test_pack.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,6 @@ def rewind_streams():
197197
obj.stream.seek(0)
198198
# END utility
199199
for ppath, ipath, num_obj in zip((pack_path, ) * 2, (index_path, None), (len(pack_objs), None)):
200-
pfile = open(ppath, 'wb')
201200
iwrite = None
202201
if ipath:
203202
ifile = open(ipath, 'wb')
@@ -210,8 +209,8 @@ def rewind_streams():
210209
# END rewind streams
211210
iteration += 1
212211

213-
pack_sha, index_sha = PackEntity.write_pack(pack_objs, pfile.write, iwrite, object_count=num_obj)
214-
pfile.close()
212+
with open(ppath, 'wb') as pfile:
213+
pack_sha, index_sha = PackEntity.write_pack(pack_objs, pfile.write, iwrite, object_count=num_obj)
215214
assert os.path.getsize(ppath) > 100
216215

217216
# verify pack

Diff for: gitdb/test/test_util.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,15 @@ def test_basics(self):
2525
def _cmp_contents(self, file_path, data):
2626
# raise if data from file at file_path
2727
# does not match data string
28-
fp = open(file_path, "rb")
29-
try:
28+
with open(file_path, "rb") as fp:
3029
assert fp.read() == data.encode("ascii")
31-
finally:
32-
fp.close()
3330

3431
def test_lockedfd(self):
3532
my_file = tempfile.mktemp()
3633
orig_data = "hello"
3734
new_data = "world"
38-
my_file_fp = open(my_file, "wb")
39-
my_file_fp.write(orig_data.encode("ascii"))
40-
my_file_fp.close()
35+
with open(my_file, "wb") as my_file_fp:
36+
my_file_fp.write(orig_data.encode("ascii"))
4137

4238
try:
4339
lfd = LockedFD(my_file)

0 commit comments

Comments
 (0)