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 <dpursehouse@collab.net>
Tested-by: Mike Frysinger <vapier@google.com>
This commit is contained in:
Mike Frysinger 2019-11-11 05:40:22 -05:00
parent f454512619
commit 3164d40e22
7 changed files with 21 additions and 66 deletions

View File

@ -106,11 +106,8 @@ least one of these before using this command.""", file=sys.stderr)
raise EditorError('editor failed with exit status %d: %s %s' raise EditorError('editor failed with exit status %d: %s %s'
% (rc, editor, path)) % (rc, editor, path))
fd2 = open(path) with open(path) as fd2:
try:
return fd2.read() return fd2.read()
finally:
fd2.close()
finally: finally:
if fd: if fd:
os.close(fd) os.close(fd)

View File

@ -276,22 +276,16 @@ class GitConfig(object):
return None return None
try: try:
Trace(': parsing %s', self.file) Trace(': parsing %s', self.file)
fd = open(self._json) with open(self._json) as fd:
try:
return json.load(fd) return json.load(fd)
finally:
fd.close()
except (IOError, ValueError): except (IOError, ValueError):
platform_utils.remove(self._json) platform_utils.remove(self._json)
return None return None
def _SaveJson(self, cache): def _SaveJson(self, cache):
try: try:
fd = open(self._json, 'w') with open(self._json, 'w') as fd:
try:
json.dump(cache, fd, indent=2) json.dump(cache, fd, indent=2)
finally:
fd.close()
except (IOError, TypeError): except (IOError, TypeError):
if os.path.exists(self._json): if os.path.exists(self._json):
platform_utils.remove(self._json) platform_utils.remove(self._json)
@ -773,15 +767,12 @@ class Branch(object):
self._Set('merge', self.merge) self._Set('merge', self.merge)
else: else:
fd = open(self._config.file, 'a') with open(self._config.file, 'a') as fd:
try:
fd.write('[branch "%s"]\n' % self.name) fd.write('[branch "%s"]\n' % self.name)
if self.remote: if self.remote:
fd.write('\tremote = %s\n' % self.remote.name) fd.write('\tremote = %s\n' % self.remote.name)
if self.merge: if self.merge:
fd.write('\tmerge = %s\n' % self.merge) fd.write('\tmerge = %s\n' % self.merge)
finally:
fd.close()
def _Set(self, key, value): def _Set(self, key, value):
key = 'branch.%s.%s' % (self.name, key) key = 'branch.%s.%s' % (self.name, key)

View File

@ -141,18 +141,11 @@ class GitRefs(object):
def _ReadLoose1(self, path, name): def _ReadLoose1(self, path, name):
try: try:
fd = open(path) with open(path) as fd:
except IOError:
return
try:
try:
mtime = os.path.getmtime(path) mtime = os.path.getmtime(path)
ref_id = fd.readline() ref_id = fd.readline()
except (IOError, OSError): except (IOError, OSError):
return return
finally:
fd.close()
try: try:
ref_id = ref_id.decode() ref_id = ref_id.decode()

View File

@ -58,11 +58,8 @@ else:
def _lwrite(path, content): def _lwrite(path, content):
lock = '%s.lock' % path lock = '%s.lock' % path
fd = open(lock, 'w') with open(lock, 'w') as fd:
try:
fd.write(content) fd.write(content)
finally:
fd.close()
try: try:
platform_utils.rename(lock, path) platform_utils.rename(lock, path)
@ -1393,12 +1390,9 @@ class Project(object):
if is_new: if is_new:
alt = os.path.join(self.gitdir, 'objects/info/alternates') alt = os.path.join(self.gitdir, 'objects/info/alternates')
try: try:
fd = open(alt) with open(alt) as fd:
try:
# This works for both absolute and relative alternate directories. # This works for both absolute and relative alternate directories.
alt_dir = os.path.join(self.objdir, 'objects', fd.readline().rstrip()) alt_dir = os.path.join(self.objdir, 'objects', fd.readline().rstrip())
finally:
fd.close()
except IOError: except IOError:
alt_dir = None alt_dir = None
else: else:
@ -2893,13 +2887,10 @@ class Project(object):
else: else:
path = os.path.join(self._project.worktree, '.git', HEAD) path = os.path.join(self._project.worktree, '.git', HEAD)
try: try:
fd = open(path) with open(path) as fd:
line = fd.readline()
except IOError as e: except IOError as e:
raise NoManifestException(path, str(e)) raise NoManifestException(path, str(e))
try:
line = fd.readline()
finally:
fd.close()
try: try:
line = line.decode() line = line.decode()
except AttributeError: except AttributeError:

5
repo
View File

@ -513,9 +513,8 @@ def SetupGnuPG(quiet):
sys.exit(1) sys.exit(1)
print() print()
fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w') with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n') fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
fd.close()
return True return True

View File

@ -40,10 +40,9 @@ in a Git repository for use during future 'repo init' invocations.
helptext = self._helpDescription + '\n' helptext = self._helpDescription + '\n'
r = os.path.dirname(__file__) r = os.path.dirname(__file__)
r = os.path.dirname(r) r = os.path.dirname(r)
fd = open(os.path.join(r, 'docs', 'manifest-format.md')) with open(os.path.join(r, 'docs', 'manifest-format.md')) as fd:
for line in fd: for line in fd:
helptext += line helptext += line
fd.close()
return helptext return helptext
def _Options(self, p): def _Options(self, p):

View File

@ -692,11 +692,8 @@ later is required to fix a server side protocol bug.
old_project_paths = [] old_project_paths = []
if os.path.exists(file_path): if os.path.exists(file_path):
fd = open(file_path, 'r') with open(file_path, 'r') as fd:
try:
old_project_paths = fd.read().split('\n') old_project_paths = fd.read().split('\n')
finally:
fd.close()
# In reversed order, so subfolders are deleted before parent folder. # In reversed order, so subfolders are deleted before parent folder.
for path in sorted(old_project_paths, reverse=True): for path in sorted(old_project_paths, reverse=True):
if not path: if not path:
@ -731,12 +728,9 @@ later is required to fix a server side protocol bug.
return 1 return 1
new_project_paths.sort() new_project_paths.sort()
fd = open(file_path, 'w') with open(file_path, 'w') as fd:
try:
fd.write('\n'.join(new_project_paths)) fd.write('\n'.join(new_project_paths))
fd.write('\n') fd.write('\n')
finally:
fd.close()
return 0 return 0
def _SmartSyncSetup(self, opt, smart_sync_manifest_path): def _SmartSyncSetup(self, opt, smart_sync_manifest_path):
@ -809,11 +803,8 @@ later is required to fix a server side protocol bug.
if success: if success:
manifest_name = os.path.basename(smart_sync_manifest_path) manifest_name = os.path.basename(smart_sync_manifest_path)
try: try:
f = open(smart_sync_manifest_path, 'w') with open(smart_sync_manifest_path, 'w') as f:
try:
f.write(manifest_str) f.write(manifest_str)
finally:
f.close()
except IOError as e: except IOError as e:
print('error: cannot write manifest to %s:\n%s' print('error: cannot write manifest to %s:\n%s'
% (smart_sync_manifest_path, e), % (smart_sync_manifest_path, e),
@ -1102,11 +1093,8 @@ class _FetchTimes(object):
def _Load(self): def _Load(self):
if self._times is None: if self._times is None:
try: try:
f = open(self._path) with open(self._path) as f:
try:
self._times = json.load(f) self._times = json.load(f)
finally:
f.close()
except (IOError, ValueError): except (IOError, ValueError):
try: try:
platform_utils.remove(self._path) platform_utils.remove(self._path)
@ -1126,11 +1114,8 @@ class _FetchTimes(object):
del self._times[name] del self._times[name]
try: try:
f = open(self._path, 'w') with open(self._path, 'w') as f:
try:
json.dump(self._times, f, indent=2) json.dump(self._times, f, indent=2)
finally:
f.close()
except (IOError, TypeError): except (IOError, TypeError):
try: try:
platform_utils.remove(self._path) platform_utils.remove(self._path)