split out writing to tty logic for reuse
authorJacob Lifshay <programmerjake@gmail.com>
Wed, 23 Aug 2023 00:48:42 +0000 (17:48 -0700)
committerJacob Lifshay <programmerjake@gmail.com>
Wed, 23 Aug 2023 00:48:42 +0000 (17:48 -0700)
src/budget_sync/util.py

index 7a4170c24105afbeb37156eb5db74d9c014f0b24..ac9ec7bac434152f002e1a97fa5bd8187f22b3cf 100644 (file)
@@ -35,9 +35,8 @@ class BugStatus(Enum):
             raise
 
 
-def all_bugs(bz: Bugzilla) -> Iterator[Bug]:
-    chunk_start = 1
-    chunk_size = 100
+@contextmanager
+def tty_out():
     try:
         if hasattr(os, "ctermid"):
             term = open(os.ctermid(), "wt", encoding="utf-8")
@@ -49,6 +48,16 @@ def all_bugs(bz: Bugzilla) -> Iterator[Bug]:
         # no terminal available
         term = None
     try:  # can't use `with` since it doesn't work with None
+        yield term
+    finally:
+        if term is not None:
+            term.close()
+
+
+def all_bugs(bz: Bugzilla) -> Iterator[Bug]:
+    chunk_start = 1
+    chunk_size = 100
+    with tty_out() as term:
         while True:
             bugs = list(range(chunk_start, chunk_start + chunk_size))
             bugs = bz.getbugs(bugs)
@@ -60,9 +69,6 @@ def all_bugs(bz: Bugzilla) -> Iterator[Bug]:
             if len(bugs) == 0:
                 return
             yield from bugs
-    finally:
-        if term is not None:
-            term.close()
 
 
 class SequencePrettyPrinter: