From 3164d40e2247d42537aef8e80fa7e048e14bec9f Mon Sep 17 00:00:00 2001 From: Mike Frysinger Date: Mon, 11 Nov 2019 05:40:22 -0500 Subject: use open context managers in more places Use open() as a context manager to simplify the close logic and make the code easier to read & understand. This is also more Pythonic. Change-Id: I579d03cca86f99b2c6c6a1f557f6e5704e2515a7 Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/244734 Reviewed-by: David Pursehouse Tested-by: Mike Frysinger --- project.py | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) (limited to 'project.py') diff --git a/project.py b/project.py index a2a3adc8..6a48c23a 100755 --- a/project.py +++ b/project.py @@ -58,11 +58,8 @@ else: def _lwrite(path, content): lock = '%s.lock' % path - fd = open(lock, 'w') - try: + with open(lock, 'w') as fd: fd.write(content) - finally: - fd.close() try: platform_utils.rename(lock, path) @@ -1393,12 +1390,9 @@ class Project(object): if is_new: alt = os.path.join(self.gitdir, 'objects/info/alternates') try: - fd = open(alt) - try: + with open(alt) as fd: # This works for both absolute and relative alternate directories. alt_dir = os.path.join(self.objdir, 'objects', fd.readline().rstrip()) - finally: - fd.close() except IOError: alt_dir = None else: @@ -2893,13 +2887,10 @@ class Project(object): else: path = os.path.join(self._project.worktree, '.git', HEAD) try: - fd = open(path) + with open(path) as fd: + line = fd.readline() except IOError as e: raise NoManifestException(path, str(e)) - try: - line = fd.readline() - finally: - fd.close() try: line = line.decode() except AttributeError: -- cgit v1.2.3-54-g00ecf