[PATCH] Use atomic_ofstream as Context Manager i.e., with-statement contexts

Florian Schmaus <[email protected]> Tue, 9 Mar 2021 08:25:59 +0100
Newsgroups gmane.linux.gentoo.portage.devel
Message-ID <[email protected]>
With [1: e93e6d65fa1c] atomic_ofstream became a Context Manager. This
commit transforms three further call sites of atomic_ofstream() to use
with-statement contexts for easier readability and increased
robustness against resource leaks.

1: e93e6d65fa1ca75f676a227f7918f8b6d747425c
   Make atomic_ofstream a Context Manager

Signed-off-by: Florian Schmaus <[email protected]>
---
 lib/_emerge/BlockerCache.py            |  6 +++---
 lib/portage/dbapi/_VdbMetadataDelta.py | 11 +++++------
 lib/portage/dbapi/vartree.py           |  6 +++---
 3 files changed, 11 insertions(+), 12 deletions(-)

diff --git a/lib/_emerge/BlockerCache.py b/lib/_emerge/BlockerCache.py
index 8154d9adee07..035f2212d3c6 100644
--- a/lib/_emerge/BlockerCache.py
+++ b/lib/_emerge/BlockerCache.py
@@ -133,9 +133,9 @@ class BlockerCache(portage.cache.mappings.MutableMapping):
 		if len(self._modified) >= self._cache_threshold and \
 			secpass >= 2:
 			try:
-				f = portage.util.atomic_ofstream(self._cache_filename, mode='wb')
-				pickle.dump(self._cache_data, f, protocol=2)
-				f.close()
+				with portage.util.atomic_ofstream(self._cache_filename, mode='wb') as f:
+					pickle.dump(self._cache_data, f, protocol=2)
+
 				portage.util.apply_secpass_permissions(
 					self._cache_filename, gid=portage.portage_gid, mode=0o644)
 			except (IOError, OSError):
diff --git a/lib/portage/dbapi/_VdbMetadataDelta.py b/lib/portage/dbapi/_VdbMetadataDelta.py
index ffdc0b361da7..568e1964a6b9 100644
--- a/lib/portage/dbapi/_VdbMetadataDelta.py
+++ b/lib/portage/dbapi/_VdbMetadataDelta.py
@@ -18,13 +18,12 @@ class VdbMetadataDelta:
 		self._vardb = vardb
 
 	def initialize(self, timestamp):
-		f = atomic_ofstream(self._vardb._cache_delta_filename, 'w',
-			encoding=_encodings['repo.content'], errors='strict')
-		json.dump({
-			"version": self._format_version,
-			"timestamp": timestamp
+		with atomic_ofstream(self._vardb._cache_delta_filename, 'w',
+			encoding=_encodings['repo.content'], errors='strict') as f:
+			json.dump({
+				"version": self._format_version,
+				"timestamp": timestamp
 			}, f, ensure_ascii=False)
-		f.close()
 
 	def load(self):
 
diff --git a/lib/portage/dbapi/vartree.py b/lib/portage/dbapi/vartree.py
index 826083eaef17..5ae035baf601 100644
--- a/lib/portage/dbapi/vartree.py
+++ b/lib/portage/dbapi/vartree.py
@@ -614,9 +614,9 @@ class vardbapi(dbapi):
 			timestamp = time.time()
 			self._aux_cache["timestamp"] = timestamp
 
-			f = atomic_ofstream(self._aux_cache_filename, 'wb')
-			pickle.dump(self._aux_cache, f, protocol=2)
-			f.close()
+			with atomic_ofstream(self._aux_cache_filename, 'wb') as f:
+				pickle.dump(self._aux_cache, f, protocol=2)
+
 			apply_secpass_permissions(
 				self._aux_cache_filename, mode=0o644)
 
-- 
2.30.1