[projects/pld-builder.new] ruff: open files with context managers

arekm arekm at pld-linux.org
Mon Oct 26 17:18:17 CET 2026


commit 44e7fa8e62d10bc3bc15b176d92bb99ddfe32514
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Sat Oct 24 11:12:32 2026 +0200

    ruff: open files with context managers
    
    Queue and lock files stay open on purpose, flock needs them.

 PLD_Builder/acl.py                    |  3 +-
 PLD_Builder/blacklist.py              | 15 ++++----
 PLD_Builder/bqueue.py                 | 13 +++----
 PLD_Builder/buildlogs.py              |  5 +--
 PLD_Builder/config.py                 |  3 +-
 PLD_Builder/file_sender.py            | 48 +++++++++++------------
 PLD_Builder/load_balancer.py          | 30 +++++++--------
 PLD_Builder/lock.py                   |  2 +-
 PLD_Builder/log.py                    |  7 ++--
 PLD_Builder/mailer.py                 | 27 ++++++-------
 PLD_Builder/maintainer.py             |  3 +-
 PLD_Builder/notifyq.py                |  5 +--
 PLD_Builder/report.py                 | 71 +++++++++++++++++------------------
 PLD_Builder/request_fetcher.py        | 17 ++++-----
 PLD_Builder/request_handler.py        | 13 +++----
 PLD_Builder/request_handler_server.py | 14 ++-----
 PLD_Builder/rpm_builder.py            | 16 ++++----
 PLD_Builder/srpm_builder.py           | 14 +++----
 PLD_Builder/util.py                   | 26 ++++++-------
 19 files changed, 152 insertions(+), 180 deletions(-)
---
diff --git a/PLD_Builder/acl.py b/PLD_Builder/acl.py
index c152711..a37e8b9 100644
--- a/PLD_Builder/acl.py
+++ b/PLD_Builder/acl.py
@@ -106,7 +106,8 @@ class ACL_Conf:
         self.current_user = None
         status.push("reading acl.conf")
         p = ConfigParser.ConfigParser()
-        p.read_file(open(path.acl_conf))
+        with open(path.acl_conf) as f:
+            p.read_file(f)
         self.users = {}
         for login in p.sections():
             if login in self.users:
diff --git a/PLD_Builder/blacklist.py b/PLD_Builder/blacklist.py
index 70433ee..8a0abff 100644
--- a/PLD_Builder/blacklist.py
+++ b/PLD_Builder/blacklist.py
@@ -25,14 +25,13 @@ class Blacklist_File:
         self.blacklist_file_mtime = os.stat(path.blacklist_file)[stat.ST_MTIME]
         self.blacklist = set()
         status.push("reading package-blacklist")
-        f = open(path.blacklist_file)
-        for l in f:
-            p = l.rstrip()
-            if re.match(r"^#.*", p):
-                continue
-            self.blacklist.add(p)
-            log.notice(f"blacklist added: {p}")
-        f.close()
+        with open(path.blacklist_file) as f:
+            for l in f:
+                p = l.rstrip()
+                if re.match(r"^#.*", p):
+                    continue
+                self.blacklist.add(p)
+                log.notice(f"blacklist added: {p}")
         status.pop()
 
     def package(self, p):
diff --git a/PLD_Builder/bqueue.py b/PLD_Builder/bqueue.py
index 14c5bf3..393c56e 100644
--- a/PLD_Builder/bqueue.py
+++ b/PLD_Builder/bqueue.py
@@ -3,7 +3,6 @@
 import fcntl
 import gzip
 import os
-import re
 import tempfile
 from io import StringIO
 
@@ -66,20 +65,18 @@ class B_Queue:
 
     # read possibly compressed, signed queue
     def read_signed(self):
-        if re.search(r"\.gz$", self.name):
-            f = gzip.open(self.name)
-        else:
-            f = open(self.name)
-        (signers, body) = gpg.verify_sig(f.read())
+        opener = gzip.open if self.name.endswith(".gz") else open
+        with opener(self.name) as f:
+            (signers, body) = gpg.verify_sig(f.read())
         self.signers = signers
         self.requests = request.parse_requests(body)
 
     def _open(self):
         if self.fd == None:
             if os.access(self.name, os.F_OK):
-                self.fd = open(self.name, "r+")
+                self.fd = open(self.name, "r+")  # noqa: SIM115 - held open for flock
             else:
-                self.fd = open(self.name, "w+")
+                self.fd = open(self.name, "w+")  # noqa: SIM115
 
     def read(self):
         self._open()
diff --git a/PLD_Builder/buildlogs.py b/PLD_Builder/buildlogs.py
index 3a47383..6d46fc5 100644
--- a/PLD_Builder/buildlogs.py
+++ b/PLD_Builder/buildlogs.py
@@ -41,9 +41,8 @@ class Buildlogs_Queue:
         try:
             with open(logfile, 'rb') as f_in, bz2.open(qfile, 'wb', compresslevel=9) as f_out:
                 shutil.copyfileobj(f_in, f_out)
-            f = open(qfile + ".info", "w")
-            f.write(f"Status: {s}\nEND\n")
-            f.close()
+            with open(qfile + ".info", "w") as f:
+                f.write(f"Status: {s}\nEND\n")
         except OSError as e:
             # queueing it anyway would make file_sender retry a missing file forever
             log.error(f"queueing buildlog {logfile} failed, not sending it: {e}")
diff --git a/PLD_Builder/config.py b/PLD_Builder/config.py
index e8f079c..08ddee0 100644
--- a/PLD_Builder/config.py
+++ b/PLD_Builder/config.py
@@ -43,7 +43,8 @@ class Builder_Conf:
             else:
                 log.panic(f"cannot find {builder}::{o}")
 
-        p.read_file(open(path.builder_conf))
+        with open(path.builder_conf) as f:
+            p.read_file(f)
 
         self.admin_email = get("admin_email")
         self.email = self.admin_email
diff --git a/PLD_Builder/file_sender.py b/PLD_Builder/file_sender.py
index 63f8e78..b7b04c2 100644
--- a/PLD_Builder/file_sender.py
+++ b/PLD_Builder/file_sender.py
@@ -20,19 +20,17 @@ from config import config, init_conf
 retries_times = [5 * 60, 5 * 60, 10 * 60, 10 * 60, 30 * 60, 60 * 60]
 
 def read_name_val(file):
-    f = open(file)
     r = {'_file': file[:-5], '_desc': file}
     rx = re.compile(r"^([^:]+)\s*:(.*)$")
-    for l in f:
-        if l == "END\n":
-            f.close()
-            return r
-        m = rx.search(l)
-        if m:
-            r[m.group(1)] = m.group(2).strip()
-        else:
-            break
-    f.close()
+    with open(file) as f:
+        for l in f:
+            if l == "END\n":
+                return r
+            m = rx.search(l)
+            if m:
+                r[m.group(1)] = m.group(2).strip()
+            else:
+                break
     return None
 
 # the senders return None on success, otherwise a description of the problem
@@ -54,13 +52,12 @@ def copy_file(src, target):
     return None
 
 def rsync_file(src, target, host):
-    p = open(path.rsync_password_file, "r")
     password = ""
-    for l in p:
-        l = l.split()
-        if len(l) >= 2 and l[0] == host:
-            password = l[1]
-    p.close()
+    with open(path.rsync_password_file) as p:
+        for l in p:
+            l = l.split()
+            if len(l) >= 2 and l[0] == host:
+                password = l[1]
 
     # NOTE: directing STDIN to /dev/null, does not make rsync to skip asking
     # password, it opens /dev/tty and still asks if password is needed and
@@ -76,9 +73,8 @@ def rsync_ssh_file(src, target):
 
 def post_file(src, url):
     try:
-        f = open(src, 'r')
-        data = f.read().encode('utf-8')
-        f.close()
+        with open(src) as f:
+            data = f.read().encode('utf-8')
         headers = { 'X-Filename' : os.path.basename(src) }
         req = urllib.request.Request(url, data=data, headers=headers)
         f = urllib.request.urlopen(req)
@@ -116,10 +112,9 @@ def send_file(src, target):
 def maybe_flush_queue(dir):
     retry_delay = 0
     try:
-        f = open(dir + "/retry-at")
-        last_retry = int(f.readline().strip())
-        retry_delay = int(f.readline().strip())
-        f.close()
+        with open(dir + "/retry-at") as f:
+            last_retry = int(f.readline().strip())
+            retry_delay = int(f.readline().strip())
         if last_retry + retry_delay > time.time():
             return
         os.unlink(dir + "/retry-at")
@@ -129,14 +124,13 @@ def maybe_flush_queue(dir):
     status.push(f"flushing {dir}")
 
     if flush_queue(dir):
-        f = open(dir + "/retry-at", "w")
         if retry_delay in retries_times:
             idx = retries_times.index(retry_delay)
             if idx < len(retries_times) - 1: idx += 1
         else:
             idx = 0
-        f.write(f"{int(time.time())}\n{retries_times[idx]}\n")
-        f.close()
+        with open(dir + "/retry-at", "w") as f:
+            f.write(f"{int(time.time())}\n{retries_times[idx]}\n")
 
     status.pop()
 
diff --git a/PLD_Builder/load_balancer.py b/PLD_Builder/load_balancer.py
index 6e7f70f..0068d53 100644
--- a/PLD_Builder/load_balancer.py
+++ b/PLD_Builder/load_balancer.py
@@ -24,26 +24,22 @@ def builders_order():
         bl.append(b)
 
     lck = lock.lock("got-lock")
-    f = open(path.got_lock_file, "r+")
-    line_no = 0
+    with open(path.got_lock_file, "r+") as f:
+        for line_no, l in enumerate(f, 1):
+            b = l.strip()
+            if b in bs:
+                bs[b] = line_no
+            else:
+                log.alert(f"found strange lock in got-lock: {b}")
 
-    for l in f:
-        line_no += 1
-        b = l.strip()
-        if b in bs:
-            bs[b] = line_no
-        else:
-            log.alert(f"found strange lock in got-lock: {b}")
+        def mycmp(b1, b2):
+            return util.cmp(bs[b1], bs[b2])
 
-    def mycmp(b1, b2):
-        return util.cmp(bs[b1], bs[b2])
+        bl.sort(key=util.cmp_to_key(mycmp))
 
-    bl.sort(key=util.cmp_to_key(mycmp))
-
-    f.seek(0)
-    f.truncate(0)
-    for l in bl: f.write(l + "\n")
-    f.close()
+        f.seek(0)
+        f.truncate(0)
+        for l in bl: f.write(l + "\n")
     lck.close()
 
     return bl
diff --git a/PLD_Builder/lock.py b/PLD_Builder/lock.py
index ce5e94a..33e73c1 100644
--- a/PLD_Builder/lock.py
+++ b/PLD_Builder/lock.py
@@ -7,7 +7,7 @@ import path
 locks_list = []
 
 def lock(n, non_block = 0):
-    f = open(path.lock_dir + '/' + n, "a")
+    f = open(path.lock_dir + '/' + n, "a")  # noqa: SIM115 - the lock lives as long as the file
     # blah, otherwise it gets garbage collected and doesn't work
     locks_list.append(f)
     if non_block:
diff --git a/PLD_Builder/log.py b/PLD_Builder/log.py
index 8ff12bc..f52a756 100644
--- a/PLD_Builder/log.py
+++ b/PLD_Builder/log.py
@@ -23,16 +23,15 @@ def log(p, s):
             syslog.syslog(p, str(s))
         except TypeError:
             syslog.syslog(p, repr(s))
-    f = open(path.log_file, "a")
-    f.write(f"{time.asctime()} [{builder}]: {s} [{os.path.basename(sys.argv[0])}]\n")
-    f.close()
+    with open(path.log_file, "a") as f:
+        f.write(f"{time.asctime()} [{builder}]: {s} [{os.path.basename(sys.argv[0])}]\n")
 
 class Panic(Exception):
     pass
 
 def panic(s):
     log(syslog.LOG_ALERT, f"PANIC: {s}")
-    raise Panic(f"PANIC: {str(s)}")
+    raise Panic(f"PANIC: {s}")
 
 def alert(s):
     log(syslog.LOG_ALERT, f"alert: {s}")
diff --git a/PLD_Builder/mailer.py b/PLD_Builder/mailer.py
index fa470ae..04f6768 100644
--- a/PLD_Builder/mailer.py
+++ b/PLD_Builder/mailer.py
@@ -41,20 +41,21 @@ class Message:
         s = os.stat(logfile)
         if s.st_size > 50000:
             # just head and tail
-            f = open(logfile)
-            line_cnt = 0
-            for l in f:
-                line_cnt += 1
-            f.seek(0)
-            line = 0
-            for l in f:
-                if line < 100 or line > line_cnt - 100:
-                    self.body.write(util.to_str(l))
-                if line == line_cnt - 100:
-                    self.body.write("\n\n[...]\n\n")
-                line += 1
+            with open(logfile) as f:
+                line_cnt = 0
+                for l in f:
+                    line_cnt += 1
+                f.seek(0)
+                line = 0
+                for l in f:
+                    if line < 100 or line > line_cnt - 100:
+                        self.body.write(util.to_str(l))
+                    if line == line_cnt - 100:
+                        self.body.write("\n\n[...]\n\n")
+                    line += 1
         else:
-            shutil.copyfileobj(open(logfile), self.body)
+            with open(logfile) as f:
+                shutil.copyfileobj(f, self.body)
 
     def set_std_headers(self):
         self.headers["Date"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
diff --git a/PLD_Builder/maintainer.py b/PLD_Builder/maintainer.py
index 6dc8663..a2d19f5 100644
--- a/PLD_Builder/maintainer.py
+++ b/PLD_Builder/maintainer.py
@@ -26,7 +26,8 @@ def send_rpmqa():
     tmp = path.build_dir + '/' + util.uuid() + '/'
     os.mkdir(tmp)
     log = tmp + config.rpmqa_filename
-    open(log, 'a').write("Query done at: {}\n".format(datetime.datetime.now().isoformat(' ')))
+    with open(log, 'a') as f:
+        f.write("Query done at: {}\n".format(datetime.datetime.now().isoformat(' ')))
     chroot.run("rpm -qa|sort", logfile=log)
     os.chmod(log,0o0644)
     ftp.init(rpmqa=True)
diff --git a/PLD_Builder/notifyq.py b/PLD_Builder/notifyq.py
index e0c7507..0867f40 100644
--- a/PLD_Builder/notifyq.py
+++ b/PLD_Builder/notifyq.py
@@ -18,9 +18,8 @@ class Notify_Queue:
 
     def add(self, file):
         id = util.uuid()
-        f = open(path.notify_queue_dir + '/' + id, 'w')
-        f.write(file.read())
-        f.close()
+        with open(path.notify_queue_dir + '/' + id, 'w') as f:
+            f.write(file.read())
         self.queue.append({'id': id})
 
     def flush(self):
diff --git a/PLD_Builder/report.py b/PLD_Builder/report.py
index 5843e55..4d9a5e1 100644
--- a/PLD_Builder/report.py
+++ b/PLD_Builder/report.py
@@ -8,48 +8,49 @@ from config import config
 
 def unpackaged_files(b):
     msg = "warning: Installed (but unpackaged) file(s) found:\n"
-    f = open(b.logfile)
     copy_mode = 0
     out = []
-    for l in f:
-        if l == msg:
-            copy_mode = 1
-            out.append(l)
-        elif copy_mode:
-            if l[0] != ' ' and l[0] != '\t':
-                copy_mode = 0
-            else:
+    with open(b.logfile) as f:
+        for l in f:
+            if l == msg:
+                copy_mode = 1
                 out.append(l)
+            elif copy_mode:
+                if l[0] != ' ' and l[0] != '\t':
+                    copy_mode = 0
+                else:
+                    out.append(l)
     return out
 
 def add_pld_builder_info(b):
-    l = open(b.logfile, "a")
-    l.write("Begin-PLD-Builder-Info\n")
-    l.write(f"Build-Time: {b.build_time}\n\n")
-    st = ftp.status()
-    if st != "":
-        l.write(f"Files queued for ftp:\n{st}\n")
-    ftp.clear_status()
-    l.writelines(unpackaged_files(b))
-    l.write("End-PLD-Builder-Info\n")
+    with open(b.logfile, "a") as l:
+        unpackaged = unpackaged_files(b)
+        l.write("Begin-PLD-Builder-Info\n")
+        l.write(f"Build-Time: {b.build_time}\n\n")
+        st = ftp.status()
+        if st != "":
+            l.write(f"Files queued for ftp:\n{st}\n")
+        ftp.clear_status()
+        l.writelines(unpackaged)
+        l.write("End-PLD-Builder-Info\n")
 
 def info_from_log(b, target):
     beg = "Begin-PLD-Builder-Info\n"
     end = "End-PLD-Builder-Info\n"
-    f = open(b.logfile)
     copy_mode = 0
     need_header = 1
-    for l in f:
-        if l == beg:
-            if need_header:
-                need_header = 0
-                target.write(f"\n--- {b.spec}:{b.branch}:\n")
-            copy_mode = 1
-        elif copy_mode:
-            if l == end:
-                copy_mode = 0
-            else:
-                target.write(l)
+    with open(b.logfile) as f:
+        for l in f:
+            if l == beg:
+                if need_header:
+                    need_header = 0
+                    target.write(f"\n--- {b.spec}:{b.branch}:\n")
+                copy_mode = 1
+            elif copy_mode:
+                if l == end:
+                    copy_mode = 0
+                else:
+                    target.write(l)
 
 def send_report(r, is_src = False):
     s_failed = ' '.join([b.spec for b in r.batches if b.build_failed])
@@ -117,9 +118,8 @@ def send_cia_report(r, is_src = False):
     m.set_header("X-builder", "PLD")
 
     # get header of xml message from file
-    f = open(path.root_dir + '/PLD_Builder/cia-head.xml')
-    m.write(f.read())
-    f.close()
+    with open(path.root_dir + '/PLD_Builder/cia-head.xml') as f:
+        m.write(f.read())
 
     # write in iteration list and status of all processed files
     for b in r.batches:
@@ -131,9 +131,8 @@ def send_cia_report(r, is_src = False):
         m.write('</package>\n')
 
     # get footer of xml message from file
-    f = open(path.root_dir + '/PLD_Builder/cia-foot.xml')
-    m.write(f.read())
-    f.close()
+    with open(path.root_dir + '/PLD_Builder/cia-foot.xml') as f:
+        m.write(f.read())
 
     # send the e-mail
     m.send()
diff --git a/PLD_Builder/request_fetcher.py b/PLD_Builder/request_fetcher.py
index 13632c3..376c330 100644
--- a/PLD_Builder/request_fetcher.py
+++ b/PLD_Builder/request_fetcher.py
@@ -28,13 +28,11 @@ def alarmalarm(signum, frame):
 
 def has_new(control_url):
     global last_count
-    cnt_f = open(path.last_req_no_file)
-    try:
-        last_count = int(cnt_f.readline().strip())
-    except ValueError:
-        last_count = 0
-
-    cnt_f.close()
+    with open(path.last_req_no_file) as cnt_f:
+        try:
+            last_count = int(cnt_f.readline().strip())
+        except ValueError:
+            last_count = 0
     f = None
     socket.setdefaulttimeout(240)
     signal.signal(signal.SIGALRM, alarmalarm)
@@ -126,9 +124,8 @@ def main():
                 q_new.append(r)
         for b in config.binary_builders:
             handle_reqs(b, q_new)
-        f = open(path.last_req_no_file, "w")
-        f.write(f"{max_no}\n")
-        f.close()
+        with open(path.last_req_no_file, "w") as f:
+            f.write(f"{max_no}\n")
     status.pop()
     lck.close()
 
diff --git a/PLD_Builder/request_handler.py b/PLD_Builder/request_handler.py
index 42eee48..1228268 100644
--- a/PLD_Builder/request_handler.py
+++ b/PLD_Builder/request_handler.py
@@ -24,13 +24,12 @@ from mailer import Message
 def check_double_id(id):
     id_nl = id + "\n"
 
-    ids = open(path.processed_ids_file)
-    for i in ids:
-        if i == id_nl:
-            # FIXME: security email here?
-            log.alert(f"request {id} already processed")
-            return 1
-    ids.close()
+    with open(path.processed_ids_file) as ids:
+        for i in ids:
+            if i == id_nl:
+                # FIXME: security email here?
+                log.alert(f"request {id} already processed")
+                return 1
 
     return 0
 
diff --git a/PLD_Builder/request_handler_server.py b/PLD_Builder/request_handler_server.py
index 1b2acf7..8139c4b 100644
--- a/PLD_Builder/request_handler_server.py
+++ b/PLD_Builder/request_handler_server.py
@@ -109,11 +109,8 @@ def write_css():
         return
 
     old_umask = os.umask(0o0022)
-    r = open(css_src, 'r')
-    f = open(css_file, "w")
-    f.write(r.read())
-    f.close()
-    r.close()
+    with open(css_src) as r, open(css_file, "w") as f:
+        f.write(r.read())
     os.umask(old_umask)
 
 def write_js():
@@ -124,11 +121,8 @@ def write_js():
         return
 
     old_umask = os.umask(0o0022)
-    r = open(js_src, 'r')
-    f = open(js_file, 'w')
-    f.write(r.read())
-    f.close()
-    r.close()
+    with open(js_src) as r, open(js_file, 'w') as f:
+        f.write(r.read())
     os.umask(old_umask)
 
 def main(srv_ssl=False):
diff --git a/PLD_Builder/rpm_builder.py b/PLD_Builder/rpm_builder.py
index 5bf4111..174f0c8 100644
--- a/PLD_Builder/rpm_builder.py
+++ b/PLD_Builder/rpm_builder.py
@@ -326,9 +326,8 @@ def build_rpm(r, b):
 
     if config.gen_upinfo and b.files != [] and 'test-build' not in r.flags:
         fname = r.tmp_dir + b.src_rpm + ".uploadinfo"
-        f = open(fname, "w")
-        f.write(uploadinfo(b))
-        f.close()
+        with open(fname, "w") as f:
+            f.write(uploadinfo(b))
         ftp.add(fname, "uploadinfo")
 
     status.pop()
@@ -346,9 +345,9 @@ def handle_request(r):
 def check_load():
     do_exit = 0
     try:
-        f = open("/proc/loadavg")
-        if float(f.readline().split()[2]) > config.max_load:
-            do_exit = 1
+        with open("/proc/loadavg") as f:
+            if float(f.readline().split()[2]) > config.max_load:
+                do_exit = 1
     except:
         pass
     if do_exit:
@@ -388,9 +387,8 @@ def main_for(builder):
         # record fact that we got lock for this builder, load balancer
         # will use it for fair-queuing
         l = lock.lock("got-lock")
-        f = open(path.got_lock_file, "a")
-        f.write(config.builder + "\n")
-        f.close()
+        with open(path.got_lock_file, "a") as f:
+            f.write(config.builder + "\n")
         l.close()
     else:
         # be able to avoid locking with very low priority
diff --git a/PLD_Builder/srpm_builder.py b/PLD_Builder/srpm_builder.py
index 773528a..127ae51 100644
--- a/PLD_Builder/srpm_builder.py
+++ b/PLD_Builder/srpm_builder.py
@@ -41,7 +41,8 @@ def store_binary_request(r):
         return
     r.batches = new_b
     # store new queue and max_req_no for binary builders
-    num = int(open(path.max_req_no_file, "r").read().strip()) + 1
+    with open(path.max_req_no_file) as f:
+        num = int(f.read().strip()) + 1
 
     r.no = num
     q = B_Queue(path.req_queue_file)
@@ -82,12 +83,11 @@ def transfer_file(r, b):
 
     if config.gen_upinfo and 'test-build' not in r.flags:
         fname = path.srpms_dir + '/' + r.id + "/" + b.src_rpm + ".uploadinfo"
-        f = open(fname, "w")
-        f.write(f"info:build:{b.gb_id}:requester:{b.requester}\n"
-                f"info:build:{b.gb_id}:requester_email:{b.requester_email}\n"
-                f"file:SRPMS:{b.src_rpm}\n"
-                "END\n")
-        f.close()
+        with open(fname, "w") as f:
+            f.write(f"info:build:{b.gb_id}:requester:{b.requester}\n"
+                    f"info:build:{b.gb_id}:requester_email:{b.requester_email}\n"
+                    f"file:SRPMS:{b.src_rpm}\n"
+                    "END\n")
         ftp.add(fname, "uploadinfo")
     return True
 
diff --git a/PLD_Builder/util.py b/PLD_Builder/util.py
index 8fd2135..3ce9adb 100644
--- a/PLD_Builder/util.py
+++ b/PLD_Builder/util.py
@@ -14,9 +14,8 @@ def msg(m):
     sys.stderr.write(m)
 
 def append_to(logfile, msg):
-    f = open(logfile, "a")
-    f.write(f"{msg}\n")
-    f.close()
+    with open(logfile, "a") as f:
+        f.write(f"{msg}\n")
 
 def write_atomic(name, text):
     """Write a file that readers never see half-written."""
@@ -29,31 +28,30 @@ def clean_tmp(dir):
     os.system(f"rm -f {dir}/* 2>/dev/null; rmdir {dir} 2>/dev/null")
 
 def collect_files(logfile, basedir = "/home"):
-    f = open(logfile, 'r')
     rx = re.compile(rf"^Wrote: ({basedir}.*\.rpm)$")
     proc = re.compile(r"^Processing files:.*$")
     files = []
-    for l in reversed(list(f)):
+    with open(logfile) as f:
+        lines = list(f)
+    for l in reversed(lines):
         if proc.match(l):
             break
         m = rx.search(l)
         if m:
             files.append(m.group(1))
-    f.close()
     return files
 
 def find_last_section(logfile):
-    f = open(logfile, 'r')
     rx1 = re.compile(r"^Executing\(%(\w+)\).*$")
     rx2 = re.compile(r"^Processing (files):.*$")
     last_section = None
-    for l in f:
-        m = rx1.search(l)
-        if not m:
-            m = rx2.search(l)
-        if m:
-            last_section = m.group(1)
-    f.close()
+    with open(logfile) as f:
+        for l in f:
+            m = rx1.search(l)
+            if not m:
+                m = rx2.search(l)
+            if m:
+                last_section = m.group(1)
     return last_section
 
 def cmp_to_key(mycmp):
================================================================

---- gitweb:

http://git.pld-linux.org/gitweb.cgi/projects/pld-builder.new.git/commitdiff/ce9feb3c796ed049b6dd260a50d94d80feb1656d



More information about the pld-cvs-commit mailing list