Browse Source

Use with statement rather than try: finaly: x.close().

Gary van der Merwe 10 năm trước cách đây
mục cha
commit
692aa9914a

+ 2 - 8
dulwich/config.py

@@ -305,23 +305,17 @@ class ConfigFile(ConfigDict):
     @classmethod
     def from_path(cls, path):
         """Read configuration from a file on disk."""
-        f = GitFile(path, 'rb')
-        try:
+        with GitFile(path, 'rb') as f:
             ret = cls.from_file(f)
             ret.path = path
             return ret
-        finally:
-            f.close()
 
     def write_to_path(self, path=None):
         """Write configuration to a file on disk."""
         if path is None:
             path = self.path
-        f = GitFile(path, 'wb')
-        try:
+        with GitFile(path, 'wb') as f:
             self.write_to_file(f)
-        finally:
-            f.close()
 
     def write_to_file(self, f):
         """Write configuration to a file-like object."""

+ 2 - 8
dulwich/hooks.py

@@ -127,21 +127,15 @@ class CommitMsgShellHook(ShellHook):
         def prepare_msg(*args):
             (fd, path) = tempfile.mkstemp()
 
-            f = os.fdopen(fd, 'wb')
-            try:
+            with os.fdopen(fd, 'wb') as f:
                 f.write(args[0])
-            finally:
-                f.close()
 
             return (path,)
 
         def clean_msg(success, *args):
             if success:
-                f = open(args[0], 'rb')
-                try:
+                with open(args[0], 'rb') as f:
                     new_msg = f.read()
-                finally:
-                    f.close()
                 os.unlink(args[0])
                 return new_msg
             os.unlink(args[0])

+ 2 - 8
dulwich/index.py

@@ -438,12 +438,9 @@ def build_index_from_tree(prefix, index_path, object_store, tree_id,
                 else:
                     raise
         else:
-            f = open(full_path, 'wb')
-            try:
+            with open(full_path, 'wb') as f:
                 # Write out file
                 f.write(object_store[entry.sha].as_raw_string())
-            finally:
-                f.close()
 
             if honor_filemode:
                 os.chmod(full_path, entry.mode)
@@ -464,11 +461,8 @@ def blob_from_path_and_stat(path, st):
     """
     blob = Blob()
     if not stat.S_ISLNK(st.st_mode):
-        f = open(path, 'rb')
-        try:
+        with open(path, 'rb') as f:
             blob.data = f.read()
-        finally:
-            f.close()
     else:
         blob.data = os.readlink(path)
     return blob

+ 7 - 27
dulwich/object_store.py

@@ -431,7 +431,7 @@ class DiskObjectStore(PackBasedObjectStore):
                 return []
             raise
         ret = []
-        try:
+        with f:
             for l in f.readlines():
                 l = l.rstrip("\n")
                 if l[0] == "#":
@@ -441,8 +441,6 @@ class DiskObjectStore(PackBasedObjectStore):
                 else:
                     ret.append(os.path.join(self.path, l))
             return ret
-        finally:
-            f.close()
 
     def add_alternate_path(self, path):
         """Add an alternate path to this object store.
@@ -453,21 +451,16 @@ class DiskObjectStore(PackBasedObjectStore):
             if e.errno != errno.EEXIST:
                 raise
         alternates_path = os.path.join(self.path, "info/alternates")
-        f = GitFile(alternates_path, 'wb')
-        try:
+        with GitFile(alternates_path, 'wb') as f:
             try:
                 orig_f = open(alternates_path, 'rb')
             except (OSError, IOError) as e:
                 if e.errno != errno.ENOENT:
                     raise
             else:
-                try:
+                with orig_f:
                     f.write(orig_f.read())
-                finally:
-                    orig_f.close()
             f.write("%s\n" % path)
-        finally:
-            f.close()
 
         if not os.path.isabs(path):
             path = os.path.join(self.path, path)
@@ -600,16 +593,12 @@ class DiskObjectStore(PackBasedObjectStore):
             objects/pack directory.
         """
         fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
-        f = os.fdopen(fd, 'w+b')
-
-        try:
+        with os.fdopen(fd, 'w+b') as f:
             indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
             copier = PackStreamCopier(read_all, read_some, f,
                                       delta_iter=indexer)
             copier.verify()
             return self._complete_thin_pack(f, path, copier, indexer)
-        finally:
-            f.close()
 
     def move_in_pack(self, path):
         """Move a specific file containing a pack into the pack directory.
@@ -619,18 +608,12 @@ class DiskObjectStore(PackBasedObjectStore):
 
         :param path: Path to the pack file.
         """
-        p = PackData(path)
-        try:
+        with PackData(path) as p:
             entries = p.sorted_entries()
             basename = os.path.join(self.pack_dir,
                 "pack-%s" % iter_sha1(entry[0] for entry in entries))
-            f = GitFile(basename+".idx", "wb")
-            try:
+            with GitFile(basename+".idx", "wb") as f:
                 write_pack_index_v2(f, entries, p.get_stored_checksum())
-            finally:
-                f.close()
-        finally:
-            p.close()
         os.rename(path, basename + ".pack")
         final_pack = Pack(basename)
         self._add_known_pack(basename, final_pack)
@@ -672,11 +655,8 @@ class DiskObjectStore(PackBasedObjectStore):
         path = os.path.join(dir, obj.id[2:])
         if os.path.exists(path):
             return # Already there, no need to write again
-        f = GitFile(path, 'wb')
-        try:
+        with GitFile(path, 'wb') as f:
             f.write(obj.as_legacy_object())
-        finally:
-            f.close()
 
     @classmethod
     def init(cls, path):

+ 2 - 8
dulwich/objects.py

@@ -359,11 +359,8 @@ class ShaFile(object):
         raise NotImplementedError(self._serialize)
 
     def _parse_path(self):
-        f = GitFile(self._path, 'rb')
-        try:
+        with GitFile(self._path, 'rb') as f:
             self._parse_file(f)
-        finally:
-            f.close()
 
     def _parse_file(self, f):
         magic = self._magic
@@ -378,16 +375,13 @@ class ShaFile(object):
     @classmethod
     def from_path(cls, path):
         """Open a SHA file from disk."""
-        f = GitFile(path, 'rb')
-        try:
+        with GitFile(path, 'rb') as f:
             obj = cls.from_file(f)
             obj._path = path
             obj._sha = FixedSha(filename_to_hex(path))
             obj._file = None
             obj._magic = None
             return obj
-        finally:
-            f.close()
 
     @classmethod
     def from_file(cls, f):

+ 6 - 24
dulwich/pack.py

@@ -258,11 +258,8 @@ def load_pack_index(path):
     :param filename: Path to the index file
     :return: A PackIndex loaded from the given path
     """
-    f = GitFile(path, 'rb')
-    try:
+    with GitFile(path, 'rb') as f:
         return load_pack_index_file(path, f)
-    finally:
-        f.close()
 
 
 def _load_file_contents(f, size=None):
@@ -1128,11 +1125,8 @@ class PackData(object):
         :return: Checksum of index file
         """
         entries = self.sorted_entries(progress=progress)
-        f = GitFile(filename, 'wb')
-        try:
+        with GitFile(filename, 'wb') as f:
             return write_pack_index_v1(f, entries, self.calculate_checksum())
-        finally:
-            f.close()
 
     def create_index_v2(self, filename, progress=None):
         """Create a version 2 index file for this data file.
@@ -1142,11 +1136,8 @@ class PackData(object):
         :return: Checksum of index file
         """
         entries = self.sorted_entries(progress=progress)
-        f = GitFile(filename, 'wb')
-        try:
+        with GitFile(filename, 'wb') as f:
             return write_pack_index_v2(f, entries, self.calculate_checksum())
-        finally:
-            f.close()
 
     def create_index(self, filename, progress=None,
                      version=2):
@@ -1457,19 +1448,13 @@ def write_pack(filename, objects, deltify=None, delta_window_size=None):
     :param deltify: Whether to deltify pack objects
     :return: Tuple with checksum of pack file and index file
     """
-    f = GitFile(filename + '.pack', 'wb')
-    try:
+    with GitFile(filename + '.pack', 'wb') as f:
         entries, data_sum = write_pack_objects(f, objects,
             delta_window_size=delta_window_size, deltify=deltify)
-    finally:
-        f.close()
     entries = [(k, v[0], v[1]) for (k, v) in entries.iteritems()]
     entries.sort()
-    f = GitFile(filename + '.idx', 'wb')
-    try:
+    with GitFile(filename + '.idx', 'wb') as f:
         return data_sum, write_pack_index_v2(f, entries, data_sum)
-    finally:
-        f.close()
 
 
 def write_pack_header(f, num_objects):
@@ -1918,13 +1903,10 @@ class Pack(object):
         :return: The path of the .keep file, as a string.
         """
         keepfile_name = '%s.keep' % self._basename
-        keepfile = GitFile(keepfile_name, 'wb')
-        try:
+        with GitFile(keepfile_name, 'wb') as keepfile:
             if msg:
                 keepfile.write(msg)
                 keepfile.write('\n')
-        finally:
-            keepfile.close()
         return keepfile_name
 
 

+ 4 - 15
dulwich/refs.py

@@ -446,7 +446,7 @@ class DiskRefsContainer(RefsContainer):
                 if e.errno == errno.ENOENT:
                     return {}
                 raise
-            try:
+            with f:
                 first_line = next(iter(f)).rstrip()
                 if (first_line.startswith("# pack-refs") and " peeled" in
                         first_line):
@@ -458,8 +458,6 @@ class DiskRefsContainer(RefsContainer):
                     f.seek(0)
                     for sha, name in read_packed_refs(f):
                         self._packed_refs[name] = sha
-            finally:
-                f.close()
         return self._packed_refs
 
     def get_peeled(self, name):
@@ -493,8 +491,7 @@ class DiskRefsContainer(RefsContainer):
         """
         filename = self.refpath(name)
         try:
-            f = GitFile(filename, 'rb')
-            try:
+            with GitFile(filename, 'rb') as f:
                 header = f.read(len(SYMREF))
                 if header == SYMREF:
                     # Read only the first line
@@ -502,8 +499,6 @@ class DiskRefsContainer(RefsContainer):
                 else:
                     # Read only the first 40 bytes
                     return header + f.read(40 - len(SYMREF))
-            finally:
-                f.close()
         except IOError as e:
             if e.errno == errno.ENOENT:
                 return None
@@ -568,8 +563,7 @@ class DiskRefsContainer(RefsContainer):
             realname = name
         filename = self.refpath(realname)
         ensure_dir_exists(os.path.dirname(filename))
-        f = GitFile(filename, 'wb')
-        try:
+        with GitFile(filename, 'wb') as f:
             if old_ref is not None:
                 try:
                     # read again while holding the lock
@@ -587,8 +581,6 @@ class DiskRefsContainer(RefsContainer):
             except (OSError, IOError):
                 f.abort()
                 raise
-        finally:
-            f.close()
         return True
 
     def add_if_new(self, name, ref):
@@ -610,8 +602,7 @@ class DiskRefsContainer(RefsContainer):
         self._check_refname(realname)
         filename = self.refpath(realname)
         ensure_dir_exists(os.path.dirname(filename))
-        f = GitFile(filename, 'wb')
-        try:
+        with GitFile(filename, 'wb') as f:
             if os.path.exists(filename) or name in self.get_packed_refs():
                 f.abort()
                 return False
@@ -620,8 +611,6 @@ class DiskRefsContainer(RefsContainer):
             except (OSError, IOError):
                 f.abort()
                 raise
-        finally:
-            f.close()
         return True
 
     def remove_if_equals(self, name, old_ref):

+ 4 - 16
dulwich/repo.py

@@ -647,11 +647,8 @@ class Repo(BaseRepo):
             self._controldir = root
         elif (os.path.isfile(os.path.join(root, ".git"))):
             import re
-            f = open(os.path.join(root, ".git"), 'r')
-            try:
+            with open(os.path.join(root, ".git"), 'r') as f:
                 _, path = re.match('(gitdir: )(.+$)', f.read()).groups()
-            finally:
-                f.close()
             self.bare = False
             self._controldir = os.path.join(root, path)
         else:
@@ -689,11 +686,8 @@ class Repo(BaseRepo):
         :param contents: A string to write to the file.
         """
         path = path.lstrip(os.path.sep)
-        f = GitFile(os.path.join(self.controldir(), path), 'wb')
-        try:
+        with GitFile(os.path.join(self.controldir(), path), 'wb') as f:
             f.write(contents)
-        finally:
-            f.close()
 
     def get_named_file(self, path):
         """Get a file from the control dir with a specific name.
@@ -834,11 +828,8 @@ class Repo(BaseRepo):
         """
         path = os.path.join(self._controldir, 'description')
         try:
-            f = GitFile(path, 'rb')
-            try:
+            with GitFile(path, 'rb') as f:
                 return f.read()
-            finally:
-                f.close()
         except (IOError, OSError) as e:
             if e.errno != errno.ENOENT:
                 raise
@@ -854,11 +845,8 @@ class Repo(BaseRepo):
         """
 
         path = os.path.join(self._controldir, 'description')
-        f = open(path, 'w')
-        try:
+        with open(path, 'w') as f:
             f.write(description)
-        finally:
-            f.close()
 
     @classmethod
     def _init_maybe_bare(cls, path, bare):

+ 1 - 3
dulwich/tests/compat/server_utils.py

@@ -53,15 +53,13 @@ def _get_shallow(repo):
     if not shallow_file:
         return []
     shallows = []
-    try:
+    with shallow_file:
         for line in shallow_file:
             sha = line.strip()
             if not sha:
                 continue
             hex_to_sha(sha)
             shallows.append(sha)
-    finally:
-        shallow_file.close()
     return shallows
 
 

+ 6 - 24
dulwich/tests/test_hooks.py

@@ -55,20 +55,14 @@ exit 0
         pre_commit = os.path.join(repo_dir, 'hooks', 'pre-commit')
         hook = PreCommitShellHook(repo_dir)
 
-        f = open(pre_commit, 'wb')
-        try:
+        with open(pre_commit, 'wb') as f:
             f.write(pre_commit_fail)
-        finally:
-            f.close()
         os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         self.assertRaises(errors.HookError, hook.execute)
 
-        f = open(pre_commit, 'wb')
-        try:
+        with open(pre_commit, 'wb') as f:
             f.write(pre_commit_success)
-        finally:
-            f.close()
         os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         hook.execute()
@@ -90,20 +84,14 @@ exit 0
         commit_msg = os.path.join(repo_dir, 'hooks', 'commit-msg')
         hook = CommitMsgShellHook(repo_dir)
 
-        f = open(commit_msg, 'wb')
-        try:
+        with open(commit_msg, 'wb') as f:
             f.write(commit_msg_fail)
-        finally:
-            f.close()
         os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         self.assertRaises(errors.HookError, hook.execute, 'failed commit')
 
-        f = open(commit_msg, 'wb')
-        try:
+        with open(commit_msg, 'wb') as f:
             f.write(commit_msg_success)
-        finally:
-            f.close()
         os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         hook.execute('empty commit')
@@ -126,20 +114,14 @@ exit 1
         post_commit = os.path.join(repo_dir, 'hooks', 'post-commit')
         hook = PostCommitShellHook(repo_dir)
 
-        f = open(post_commit, 'wb')
-        try:
+        with open(post_commit, 'wb') as f:
             f.write(post_commit_msg_fail)
-        finally:
-            f.close()
         os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         self.assertRaises(errors.HookError, hook.execute)
 
-        f = open(post_commit, 'wb')
-        try:
+        with open(post_commit, 'wb') as f:
             f.write(post_commit_msg)
-        finally:
-            f.close()
         os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         hook.execute()

+ 7 - 20
dulwich/tests/test_index.py

@@ -101,16 +101,11 @@ class SimpleIndexWriterTestCase(IndexTestCase):
                     33188, 1000, 1000, 0,
                     'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 0)]
         filename = os.path.join(self.tempdir, 'test-simple-write-index')
-        x = open(filename, 'w+')
-        try:
+        with open(filename, 'w+') as x:
             write_index(x, entries)
-        finally:
-            x.close()
-        x = open(filename, 'r')
-        try:
+
+        with open(filename, 'r') as x:
             self.assertEqual(entries, list(read_index(x)))
-        finally:
-            x.close()
 
 
 class ReadIndexDictTests(IndexTestCase):
@@ -128,16 +123,11 @@ class ReadIndexDictTests(IndexTestCase):
                     33188, 1000, 1000, 0,
                     'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 0)}
         filename = os.path.join(self.tempdir, 'test-simple-write-index')
-        x = open(filename, 'w+')
-        try:
+        with open(filename, 'w+') as x:
             write_index_dict(x, entries)
-        finally:
-            x.close()
-        x = open(filename, 'r')
-        try:
+
+        with open(filename, 'r') as x:
             self.assertEqual(entries, read_index_dict(x))
-        finally:
-            x.close()
 
 
 class CommitTreeTests(TestCase):
@@ -260,11 +250,8 @@ class BuildIndexTests(TestCase):
         if symlink:
             self.assertEqual(os.readlink(path), contents)
         else:
-            f = open(path, 'rb')
-            try:
+            with open(path, 'rb') as f:
                 self.assertEqual(f.read(), contents)
-            finally:
-                f.close()
 
     def test_empty(self):
         repo_dir = tempfile.mkdtemp()

+ 16 - 16
dulwich/tests/test_object_store.py

@@ -312,25 +312,25 @@ class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):
 
     def test_add_thin_pack(self):
         o = DiskObjectStore(self.store_dir)
-        blob = make_object(Blob, data='yummy data')
-        o.add_object(blob)
-
-        f = BytesIO()
-        entries = build_pack(f, [
-          (REF_DELTA, (blob.id, 'more yummy data')),
-          ], store=o)
-        pack = o.add_thin_pack(f.read, None)
         try:
-            packed_blob_sha = sha_to_hex(entries[0][3])
-            pack.check_length_and_checksum()
-            self.assertEqual(sorted([blob.id, packed_blob_sha]), list(pack))
-            self.assertTrue(o.contains_packed(packed_blob_sha))
-            self.assertTrue(o.contains_packed(blob.id))
-            self.assertEqual((Blob.type_num, 'more yummy data'),
-                             o.get_raw(packed_blob_sha))
+            blob = make_object(Blob, data='yummy data')
+            o.add_object(blob)
+    
+            f = BytesIO()
+            entries = build_pack(f, [
+              (REF_DELTA, (blob.id, 'more yummy data')),
+              ], store=o)
+            
+            with o.add_thin_pack(f.read, None) as pack:
+                packed_blob_sha = sha_to_hex(entries[0][3])
+                pack.check_length_and_checksum()
+                self.assertEqual(sorted([blob.id, packed_blob_sha]), list(pack))
+                self.assertTrue(o.contains_packed(packed_blob_sha))
+                self.assertTrue(o.contains_packed(blob.id))
+                self.assertEqual((Blob.type_num, 'more yummy data'),
+                                 o.get_raw(packed_blob_sha))
         finally:
             o.close()
-            pack.close()
 
 
 class TreeLookupPathTests(TestCase):

+ 6 - 25
dulwich/tests/test_pack.py

@@ -305,15 +305,12 @@ class TestPack(PackTests):
             self.assertEqual(obj.sha().hexdigest(), commit_sha)
 
     def test_copy(self):
-        origpack = self.get_pack(pack1_sha)
-
-        try:
+        with self.get_pack(pack1_sha) as origpack:
             self.assertSucceeds(origpack.index.check)
             basename = os.path.join(self.tempdir, 'Elch')
             write_pack(basename, origpack.pack_tuples())
-            newpack = Pack(basename)
 
-            try:
+            with Pack(basename) as newpack:
                 self.assertEqual(origpack, newpack)
                 self.assertSucceeds(newpack.index.check)
                 self.assertEqual(origpack.name(), newpack.name())
@@ -324,10 +321,6 @@ class TestPack(PackTests):
                 orig_checksum = origpack.index.get_stored_checksum()
                 new_checksum = newpack.index.get_stored_checksum()
                 self.assertTrue(wrong_version or orig_checksum == new_checksum)
-            finally:
-                newpack.close()
-        finally:
-            origpack.close()
 
     def test_commit_obj(self):
         with self.get_pack(pack1_sha) as p:
@@ -351,12 +344,9 @@ class TestPack(PackTests):
         # file should exist
         self.assertTrue(os.path.exists(keepfile_name))
 
-        f = open(keepfile_name, 'r')
-        try:
+        with open(keepfile_name, 'r') as f:
             buf = f.read()
             self.assertEqual('', buf)
-        finally:
-            f.close()
 
     def test_keep_message(self):
         with self.get_pack(pack1_sha) as p:
@@ -370,12 +360,9 @@ class TestPack(PackTests):
         self.assertTrue(os.path.exists(keepfile_name))
 
         # and contain the right message, with a linefeed
-        f = open(keepfile_name, 'r')
-        try:
+        with open(keepfile_name, 'r') as f:
             buf = f.read()
             self.assertEqual(msg + '\n', buf)
-        finally:
-            f.close()
 
     def test_name(self):
         with self.get_pack(pack1_sha) as p:
@@ -437,15 +424,12 @@ class TestThinPack(PackTests):
         self.addCleanup(shutil.rmtree, self.pack_dir)
         self.pack_prefix = os.path.join(self.pack_dir, 'pack')
 
-        f = open(self.pack_prefix + '.pack', 'wb')
-        try:
+        with open(self.pack_prefix + '.pack', 'wb') as f:
             build_pack(f, [
                 (REF_DELTA, (self.blobs['foo'].id, 'foo1234')),
                 (Blob.type_num, 'bar'),
                 (REF_DELTA, (self.blobs['bar'].id, 'bar2468'))],
                 store=self.store)
-        finally:
-            f.close()
 
         # Index the new pack.
         with self.make_pack(True) as pack:
@@ -595,11 +579,8 @@ class BaseTestFilePackIndexWriting(BaseTestPackIndexWriting):
 
     def writeIndex(self, filename, entries, pack_checksum):
         # FIXME: Write to BytesIO instead rather than hitting disk ?
-        f = GitFile(filename, "wb")
-        try:
+        with GitFile(filename, "wb") as f:
             self._write_fn(f, entries, pack_checksum)
-        finally:
-            f.close()
 
 
 class TestMemoryIndexWriting(TestCase, BaseTestPackIndexWriting):

+ 3 - 12
dulwich/tests/test_porcelain.py

@@ -213,11 +213,8 @@ class AddTests(PorcelainTestCase):
 class RemoveTests(PorcelainTestCase):
 
     def test_remove_file(self):
-        f = open(os.path.join(self.repo.path, 'foo'), 'w')
-        try:
+        with open(os.path.join(self.repo.path, 'foo'), 'w') as f:
             f.write("BAR")
-        finally:
-            f.close()
         porcelain.add(self.repo.path, paths=["foo"])
         porcelain.rm(self.repo.path, paths=["foo"])
 
@@ -399,21 +396,15 @@ class ListTagsTests(PorcelainTestCase):
 class ResetTests(PorcelainTestCase):
 
     def test_hard_head(self):
-        f = open(os.path.join(self.repo.path, 'foo'), 'w')
-        try:
+        with open(os.path.join(self.repo.path, 'foo'), 'w') as f:
             f.write("BAR")
-        finally:
-            f.close()
         porcelain.add(self.repo.path, paths=["foo"])
         porcelain.commit(self.repo.path, message="Some message",
                 committer="Jane <jane@example.com>",
                 author="John <john@example.com>")
 
-        f = open(os.path.join(self.repo.path, 'foo'), 'w')
-        try:
+        with open(os.path.join(self.repo.path, 'foo'), 'w') as f:
             f.write("OOH")
-        finally:
-            f.close()
 
         porcelain.reset(self.repo, "hard", "HEAD")
 

+ 10 - 39
dulwich/tests/test_repository.py

@@ -54,10 +54,8 @@ class CreateRepositoryTests(TestCase):
         if not f:
             self.assertEqual(expected, None)
         else:
-            try:
+            with f:
                 self.assertEqual(expected, f.read())
-            finally:
-                f.close()
 
     def _check_repo_contents(self, repo, expect_bare):
         self.assertEqual(expect_bare, repo.bare)
@@ -173,11 +171,8 @@ class RepositoryTests(TestCase):
 
     def test_get_description(self):
         r = self._repo = open_repo('a.git')
-        f = open(os.path.join(r.path, 'description'), 'w')
-        try:
+        with open(os.path.join(r.path, 'description'), 'w') as f:
             f.write("Some description")
-        finally:
-            f.close()
         self.assertEqual("Some description", r.get_description())
 
     def test_set_description(self):
@@ -376,11 +371,8 @@ exit 0
 
         pre_commit = os.path.join(r.controldir(), 'hooks', 'pre-commit')
 
-        f = open(pre_commit, 'wb')
-        try:
+        with open(pre_commit, 'wb') as f:
             f.write(pre_commit_fail)
-        finally:
-            f.close()
         os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         self.assertRaises(errors.CommitError, r.do_commit, 'failed commit',
@@ -389,11 +381,8 @@ exit 0
                           commit_timestamp=12345, commit_timezone=0,
                           author_timestamp=12345, author_timezone=0)
 
-        f = open(pre_commit, 'wb')
-        try:
+        with open(pre_commit, 'wb') as f:
             f.write(pre_commit_success)
-        finally:
-            f.close()
         os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         commit_sha = r.do_commit(
@@ -422,11 +411,8 @@ exit 0
 
         commit_msg = os.path.join(r.controldir(), 'hooks', 'commit-msg')
 
-        f = open(commit_msg, 'wb')
-        try:
+        with open(commit_msg, 'wb') as f:
             f.write(commit_msg_fail)
-        finally:
-            f.close()
         os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         self.assertRaises(errors.CommitError, r.do_commit, 'failed commit',
@@ -435,11 +421,8 @@ exit 0
                           commit_timestamp=12345, commit_timezone=0,
                           author_timestamp=12345, author_timezone=0)
 
-        f = open(commit_msg, 'wb')
-        try:
+        with open(commit_msg, 'wb') as f:
             f.write(commit_msg_success)
-        finally:
-            f.close()
         os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         commit_sha = r.do_commit(
@@ -473,11 +456,8 @@ rm %(file)s
 
         post_commit = os.path.join(r.controldir(), 'hooks', 'post-commit')
 
-        f = open(post_commit, 'wb')
-        try:
+        with open(post_commit, 'wb') as f:
             f.write(post_commit_msg)
-        finally:
-            f.close()
         os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         commit_sha = r.do_commit(
@@ -493,11 +473,8 @@ rm %(file)s
         post_commit_msg_fail = """#!/bin/sh
 exit 1
 """
-        f = open(post_commit, 'wb')
-        try:
+        with open(post_commit, 'wb') as f:
             f.write(post_commit_msg_fail)
-        finally:
-            f.close()
         os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         warnings.simplefilter("always", UserWarning)
@@ -533,11 +510,8 @@ class BuildRepoTests(TestCase):
         self.assertEqual('ref: refs/heads/master', r.refs.read_ref('HEAD'))
         self.assertRaises(KeyError, lambda: r.refs['refs/heads/master'])
 
-        f = open(os.path.join(r.path, 'a'), 'wb')
-        try:
+        with open(os.path.join(r.path, 'a'), 'wb') as f:
             f.write('file contents')
-        finally:
-            f.close()
         r.stage(['a'])
         commit_sha = r.do_commit('msg',
                                  committer='Test Committer <test@nodomain.com>',
@@ -562,11 +536,8 @@ class BuildRepoTests(TestCase):
 
     def test_commit_modified(self):
         r = self._repo
-        f = open(os.path.join(r.path, 'a'), 'wb')
-        try:
+        with open(os.path.join(r.path, 'a'), 'wb') as f:
             f.write('new contents')
-        finally:
-            f.close()
         os.symlink('a', os.path.join(self._repo_dir, 'b'))
         r.stage(['a', 'b'])
         commit_sha = r.do_commit('modified a',