[projects/pld-builder.new] ruff: fix the remaining findings

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


commit 9f1e887e6a1f1c3cfaf2243d4a42591a1ea166ef
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Sat Oct 24 15:02:39 2026 +0200

    ruff: fix the remaining findings
    
    Excepts name what they expect; drop the unused dump_json() methods.
    ruff.toml makes PLD_Builder modules first party.

 PLD_Builder/acl.py                    |  4 +--
 PLD_Builder/blacklist.py              |  4 +--
 PLD_Builder/bqueue.py                 |  2 +-
 PLD_Builder/file_sender.py            |  4 +--
 PLD_Builder/gpg.py                    |  4 +--
 PLD_Builder/install.py                |  4 +--
 PLD_Builder/load_balancer.py          |  2 +-
 PLD_Builder/lock.py                   |  2 +-
 PLD_Builder/mailer.py                 |  8 ++----
 PLD_Builder/maintainer.py             | 12 ++++----
 PLD_Builder/report.py                 |  2 +-
 PLD_Builder/request.py                | 54 ++---------------------------------
 PLD_Builder/request_fetcher.py        |  8 +++---
 PLD_Builder/request_handler.py        |  7 ++---
 PLD_Builder/request_handler_server.py |  5 ++--
 PLD_Builder/rpm_builder.py            | 11 +++----
 PLD_Builder/srpm_builder.py           |  2 +-
 PLD_Builder/wrap.py                   |  9 +++---
 client/php-rebuild.py                 |  2 +-
 client/rebuild-kernel-packages.py     |  4 +--
 ruff.toml                             |  6 ++++
 21 files changed, 49 insertions(+), 107 deletions(-)
---
diff --git a/PLD_Builder/acl.py b/PLD_Builder/acl.py
index a37e8b9..4033307 100644
--- a/PLD_Builder/acl.py
+++ b/PLD_Builder/acl.py
@@ -58,8 +58,8 @@ class User:
             else:
                 ret = 1
             pwhat,pwhere,pbranch=priv.split(":")
-            for pbranch in pbranch.split(","):
-                priv=f"{pwhat}:{pwhere}:{pbranch}"
+            for br in pbranch.split(","):
+                priv=f"{pwhat}:{pwhere}:{br}"
                 if fnmatch.fnmatch(action, priv):
                     return ret
         return 0
diff --git a/PLD_Builder/blacklist.py b/PLD_Builder/blacklist.py
index 8a0abff..b3bcd1f 100644
--- a/PLD_Builder/blacklist.py
+++ b/PLD_Builder/blacklist.py
@@ -36,9 +36,7 @@ class Blacklist_File:
 
     def package(self, p):
 #       log.notice("blacklist check: %s (%d)" % (p, p in self.blacklist))
-        if p in self.blacklist:
-            return True
-        return False
+        return p in self.blacklist
 
     def packages(self):
         return self.blacklist
diff --git a/PLD_Builder/bqueue.py b/PLD_Builder/bqueue.py
index 393c56e..737e5c2 100644
--- a/PLD_Builder/bqueue.py
+++ b/PLD_Builder/bqueue.py
@@ -88,7 +88,7 @@ class B_Queue:
             return
         try:
             self.requests = request.parse_requests(body)
-        except Exception as e:
+        except Exception as e:  # noqa: BLE001 - any parse failure; report the file
             log.panic(f"error parsing {self.name}: {e}")
 
     def _write_to(self, f):
diff --git a/PLD_Builder/file_sender.py b/PLD_Builder/file_sender.py
index b7b04c2..35c07ed 100644
--- a/PLD_Builder/file_sender.py
+++ b/PLD_Builder/file_sender.py
@@ -79,7 +79,7 @@ def post_file(src, url):
         req = urllib.request.Request(url, data=data, headers=headers)
         f = urllib.request.urlopen(req)
         f.close()
-    except Exception as e:
+    except Exception as e:  # noqa: BLE001 - any failure means retry later
         # never empty: an empty problem would count as success
         return str(e) or repr(e)
     return None
@@ -118,7 +118,7 @@ def maybe_flush_queue(dir):
         if last_retry + retry_delay > time.time():
             return
         os.unlink(dir + "/retry-at")
-    except:
+    except (OSError, ValueError):
         pass
 
     status.push(f"flushing {dir}")
diff --git a/PLD_Builder/gpg.py b/PLD_Builder/gpg.py
index a5f1018..7eaab6e 100644
--- a/PLD_Builder/gpg.py
+++ b/PLD_Builder/gpg.py
@@ -17,12 +17,10 @@ def get_keys(buf):
         log.error("missing gnupg binary: /usr/bin/gpg")
         raise OSError('Missing gnupg binary')
 
-    d_stdout = None
-    d_stderr = None
     cmd = ['/usr/bin/gpg', '--batch', '--no-tty', '--decrypt']
     gpg_run = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
     try:
-        d_stdout, d_stderr = gpg_run.communicate(util.to_bytes(buf))
+        _, d_stderr = gpg_run.communicate(util.to_bytes(buf))
     except OSError as e:
         log.error(f"gnupg run, does gpg binary exist? : {e}")
         raise
diff --git a/PLD_Builder/install.py b/PLD_Builder/install.py
index 9c3a76a..4dd9fa8 100644
--- a/PLD_Builder/install.py
+++ b/PLD_Builder/install.py
@@ -96,7 +96,7 @@ def installed_providers(names):
     if not lines:
         return None
     # message lines contain spaces, package names cannot
-    return set(l for l in lines if l and ' ' not in l)
+    return {l for l in lines if l and ' ' not in l}
 
 def uninstall(conflicting, b):
     b.log_line("uninstalling conflicting packages")
@@ -208,7 +208,7 @@ def install_br(r, b):
     removal_rounds = 0
     while True:
         nbr = ""
-        for bre in needed.keys():
+        for bre in needed:
             nbr = nbr + " " + re.escape(bre)
         br = nbr.strip()
         # check conflicts in BRed packages
diff --git a/PLD_Builder/load_balancer.py b/PLD_Builder/load_balancer.py
index 0068d53..3adda4d 100644
--- a/PLD_Builder/load_balancer.py
+++ b/PLD_Builder/load_balancer.py
@@ -60,7 +60,7 @@ def main():
     # wait for children to die out
     try:
         while 1: os.wait()
-    except:
+    except ChildProcessError:
         pass
 
 if __name__ == '__main__':
diff --git a/PLD_Builder/lock.py b/PLD_Builder/lock.py
index 33e73c1..b7769b5 100644
--- a/PLD_Builder/lock.py
+++ b/PLD_Builder/lock.py
@@ -13,7 +13,7 @@ def lock(n, non_block = 0):
     if non_block:
         try:
             fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
-        except:
+        except OSError:
             f.close()
             return None
     else:
diff --git a/PLD_Builder/mailer.py b/PLD_Builder/mailer.py
index 04f6768..f9c65c3 100644
--- a/PLD_Builder/mailer.py
+++ b/PLD_Builder/mailer.py
@@ -42,17 +42,13 @@ class Message:
         if s.st_size > 50000:
             # just head and tail
             with open(logfile) as f:
-                line_cnt = 0
-                for l in f:
-                    line_cnt += 1
+                line_cnt = sum(1 for _ in f)
                 f.seek(0)
-                line = 0
-                for l in f:
+                for line, l in enumerate(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:
             with open(logfile) as f:
                 shutil.copyfileobj(f, self.body)
diff --git a/PLD_Builder/maintainer.py b/PLD_Builder/maintainer.py
index a2d19f5..abd2bc7 100644
--- a/PLD_Builder/maintainer.py
+++ b/PLD_Builder/maintainer.py
@@ -25,15 +25,15 @@ def clean_dir(dirname, max):
 def send_rpmqa():
     tmp = path.build_dir + '/' + util.uuid() + '/'
     os.mkdir(tmp)
-    log = tmp + config.rpmqa_filename
-    with open(log, 'a') as f:
+    rpmqa = tmp + config.rpmqa_filename
+    with open(rpmqa, '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)
+    chroot.run("rpm -qa|sort", logfile=rpmqa)
+    os.chmod(rpmqa,0o0644)
     ftp.init(rpmqa=True)
-    ftp.add(log)
+    ftp.add(rpmqa)
     ftp.flush()
-    os.unlink(log)
+    os.unlink(rpmqa)
     os.rmdir(tmp)
 
 def handle_src():
diff --git a/PLD_Builder/report.py b/PLD_Builder/report.py
index 4d9a5e1..3f8b3a6 100644
--- a/PLD_Builder/report.py
+++ b/PLD_Builder/report.py
@@ -68,7 +68,7 @@ def send_report(r, is_src = False):
     if not is_src and 'upgrade' in r.flags and False in upgrades_status:
         subject = 'upgrade failed '
 
-    subject += ' '.join((s_failed, s_ok)).strip()
+    subject += f"{s_failed} {s_ok}".strip()
 
     m = mailer.Message()
     m.set_headers(to = r.requester_email,
diff --git a/PLD_Builder/request.py b/PLD_Builder/request.py
index c21e20d..3e69bdf 100644
--- a/PLD_Builder/request.py
+++ b/PLD_Builder/request.py
@@ -121,23 +121,6 @@ class Group:
             b.dump(f)
         f.write("\n")
 
-    # return structure usable for json encoding
-    def dump_json(self):
-        batches = []
-        for b in self.batches:
-            batches.append(b.dump_json())
-
-        return dict(
-            no=self.no,
-            id=self.id,
-            time=self.time,
-            requester=self.requester,
-            priority=self.priority,
-            max_jobs=self.max_jobs,
-            flags=self.flags,
-            batches=batches,
-        )
-
     def dump_html(self, f):
         flags = escape(' '.join(self.flags))
         dt = escape(iso8601(self.time))
@@ -289,30 +272,6 @@ class Batch:
     def is_command(self):
         return self.command != ""
 
-    # return structure usable for json encoding
-    def dump_json(self):
-        return dict(
-            command=self.command,
-            command_flags=self.command_flags,
-
-            spec=self.spec,
-            branch=self.branch,
-            package=self.spec[:-5],
-            src_rpm=self.src_rpm,
-
-            bconds_with=self.bconds_with,
-            bconds_without=self.bconds_without,
-
-            kernel=self.kernel,
-            target=self.target,
-            defines=self.defines,
-
-            builders=self.builders,
-            builders_status=self.builders_status,
-            builders_status_time=self.builders_status_time,
-            builders_status_buildtime=self.builders_status_buildtime,
-        )
-
     def dump_html(self, f, rid):
         quote = urllib.parse.quote
         f.write("<li>\n")
@@ -342,7 +301,7 @@ class Batch:
                 c = "black"
             link_pre = ""
             link_post = ""
-            if (s.startswith("OK") or s.startswith("SKIP") or s.startswith("UNSUPP") or s.startswith("FAIL")) and len(self.spec) > 5:
+            if s.startswith(("OK", "SKIP", "UNSUPP", "FAIL")) and len(self.spec) > 5:
                 if self.is_command():
                     bl_name = "command"
                 else:
@@ -490,7 +449,7 @@ class Batch:
            <spec>{}</spec>
            <branch>{}</branch>
            <info>{}</info>\n""".format(self.b_id,
-                 ' '.join(list(map(lambda b: b.b_id, self.depends_on))),
+                 ' '.join(b.b_id for b in self.depends_on),
                  escape(self.src_rpm),
                  escape(' '.join(self.command_flags)), escape(self.command),
                  escape(self.spec), escape(self.branch), escape(self.info)))
@@ -554,15 +513,6 @@ class Notification:
             else:
                 log.panic(f"xml: evil notification child ({c.nodeName})")
 
-    # return structure usable for json encoding
-    def dump_json(self):
-        return dict(
-            id=self.group_id,
-            builder=self.builder,
-            batches=self.batches,
-            batches_buildtime=self.batches_buildtime,
-        )
-
     def apply_to(self, q):
         for r in q.requests:
             if r.kind == "group":
diff --git a/PLD_Builder/request_fetcher.py b/PLD_Builder/request_fetcher.py
index 376c330..89cf24e 100644
--- a/PLD_Builder/request_fetcher.py
+++ b/PLD_Builder/request_fetcher.py
@@ -43,7 +43,7 @@ def has_new(control_url):
         f = urllib.request.urlopen(req)
         count = int(f.readline().strip())
         signal.alarm(0)
-    except Exception as e:
+    except Exception as e:  # noqa: BLE001 - any fetch failure; cron retries
         signal.alarm(0)
         log.error("can't fetch {}: {}".format(control_url + "/max_req_no", e))
         sys.exit(1)
@@ -62,7 +62,7 @@ def fetch_queue(control_url):
         req = urllib.request.Request(url=control_url + "/queue.gz", headers=headers)
         f = urllib.request.urlopen(req)
         signal.alarm(0)
-    except Exception as e:
+    except Exception as e:  # noqa: BLE001 - any fetch failure; cron retries
         signal.alarm(0)
         log.error("can't fetch {}: {}".format(control_url + "/queue.gz", e))
         sys.exit(1)
@@ -73,7 +73,7 @@ def fetch_queue(control_url):
     f = gzip.GzipFile(fileobj = sio)
     try:
         fdata = f.read()
-    except Exception as e:
+    except Exception as e:  # noqa: BLE001 - truncated or corrupt download
         log.alert(f"unable to read fetched queue.gz file: {e}")
         sys.exit(1)
     (signers, body) = gpg.verify_sig(fdata)
@@ -95,7 +95,7 @@ def handle_reqs(builder, reqs):
     q.read()
     for r in reqs:
         if r.kind != 'group':
-            raise Exception(f'handle_reqs: fatal: huh? {r.kind}')
+            raise RuntimeError(f'handle_reqs: fatal: huh? {r.kind}')
         need_it = 0
         for b in r.batches:
             if builder in b.builders:
diff --git a/PLD_Builder/request_handler.py b/PLD_Builder/request_handler.py
index 1228268..355162f 100644
--- a/PLD_Builder/request_handler.py
+++ b/PLD_Builder/request_handler.py
@@ -96,10 +96,9 @@ def handle_group(r, user):
                     f"I (src rpm builder '{config.builder}') do not handle binary builder '{bld}', "
                     f"only '{binary_builders}'")
             if batch.is_command():
-                if "no-chroot" in batch.command_flags:
-                    if not user.can_do("command-no-chroot", bld):
-                        return refuse(HTTPStatus.FORBIDDEN,
-                            f"user {user.get_login()} is not allowed to command-no-chroot:{bld}")
+                if "no-chroot" in batch.command_flags and not user.can_do("command-no-chroot", bld):
+                    return refuse(HTTPStatus.FORBIDDEN,
+                        f"user {user.get_login()} is not allowed to command-no-chroot:{bld}")
                 if not user.can_do("command", bld):
                     return refuse(HTTPStatus.FORBIDDEN,
                         f"user {user.get_login()} is not allowed to command:{bld}")
diff --git a/PLD_Builder/request_handler_server.py b/PLD_Builder/request_handler_server.py
index 8139c4b..9adf687 100644
--- a/PLD_Builder/request_handler_server.py
+++ b/PLD_Builder/request_handler_server.py
@@ -1,5 +1,3 @@
-#!/usr/bin/python3
-
 import os
 import re
 import signal
@@ -150,7 +148,8 @@ def main(srv_ssl=False):
                                     keyfile=config.request_handler_server_ssl_key)
             context.load_verify_locations(cafile="/etc/certs/ca-certificates.crt")
             server.socket = context.wrap_socket(server.socket, server_side=True)
-    except Exception as e:
+    # OverflowError: a port outside 0-65535 in builder.conf
+    except (OSError, OverflowError) as e:
         log.notice(f"request_handler_server: can't start server on [{host}:{port}], ssl={srv_ssl}: {e}")
         print(f"ERROR: Can't start server on [{host}:{port}], ssl={srv_ssl}: {e}", file=sys.stderr)
         sys.exit(1)
diff --git a/PLD_Builder/rpm_builder.py b/PLD_Builder/rpm_builder.py
index 174f0c8..1ed9281 100644
--- a/PLD_Builder/rpm_builder.py
+++ b/PLD_Builder/rpm_builder.py
@@ -46,7 +46,7 @@ retry_delay = 10
 def pick_request(q):
     def mycmp(r1, r2):
         if r1.kind != 'group' or r2.kind != 'group':
-            raise Exception("non-group requests")
+            raise RuntimeError("non-group requests")
         pri_diff = util.cmp(r1.priority, r2.priority)
         if pri_diff == 0:
             return util.cmp(r1.time, r2.time)
@@ -348,7 +348,7 @@ def check_load():
         with open("/proc/loadavg") as f:
             if float(f.readline().split()[2]) > config.max_load:
                 do_exit = 1
-    except:
+    except (OSError, ValueError, IndexError):
         pass
     if do_exit:
         sys.exit(0)
@@ -409,10 +409,7 @@ def main_for(builder):
     status.pop()
 
     def otherreqs(r):
-        if r.no==req.no:
-            return False
-        else:
-            return True
+        return r.no != req.no
 
     q = B_Queue(path.queue_file + "-" + config.builder)
     q.lock(0)
@@ -425,7 +422,7 @@ def main_for(builder):
 
 def main():
     if len(sys.argv) < 2:
-        raise Exception("fatal: need to have builder name as first arg")
+        raise RuntimeError("fatal: need to have builder name as first arg")
     return main_for(sys.argv[1])
 
 if __name__ == '__main__':
diff --git a/PLD_Builder/srpm_builder.py b/PLD_Builder/srpm_builder.py
index 127ae51..85ef17e 100644
--- a/PLD_Builder/srpm_builder.py
+++ b/PLD_Builder/srpm_builder.py
@@ -22,7 +22,7 @@ from lock import lock
 def pick_request(q):
     def mycmp(r1, r2):
         if r1.kind != 'group' or r2.kind != 'group':
-            raise Exception("non-group requests")
+            raise RuntimeError("non-group requests")
         pri_diff = util.cmp(r1.priority, r2.priority)
         if pri_diff == 0:
             return util.cmp(r1.time, r2.time)
diff --git a/PLD_Builder/wrap.py b/PLD_Builder/wrap.py
index a383b23..0735e60 100644
--- a/PLD_Builder/wrap.py
+++ b/PLD_Builder/wrap.py
@@ -21,7 +21,7 @@ try:
         m.write(f"{trace}\n")
         m.write(f"during: {status.get()}\n")
         m.send()
-except:
+except ImportError:
     def sendmail(trace):
         # don't use mailer.py; it safer this way
         f = os.popen("/usr/sbin/sendmail -i -t", "w")
@@ -42,10 +42,9 @@ during: {}
 def wrap(main):
     try:
         main()
-    except:
-        exctype, value = sys.exc_info()[:2]
-        if exctype == SystemExit:
-            sys.exit(value)
+    except SystemExit:
+        raise
+    except BaseException:  # noqa: BLE001 - every other failure gets reported
         s = StringIO()
         traceback.print_exc(file = s, limit = 20)
 
diff --git a/client/php-rebuild.py b/client/php-rebuild.py
index 513bb14..86c7157 100755
--- a/client/php-rebuild.py
+++ b/client/php-rebuild.py
@@ -82,7 +82,7 @@ def fmt_ver(v):
 
 def run_cmd(cmd):
     """Run command, return (ok, output). Output is stdout on success, stderr on failure."""
-    proc = subprocess.run(cmd, capture_output=True, text=True)
+    proc = subprocess.run(cmd, check=False, capture_output=True, text=True)
     if proc.returncode == 0:
         return True, proc.stdout.strip()
     return False, proc.stderr.strip()
diff --git a/client/rebuild-kernel-packages.py b/client/rebuild-kernel-packages.py
index 9a45f65..690a6b9 100755
--- a/client/rebuild-kernel-packages.py
+++ b/client/rebuild-kernel-packages.py
@@ -175,8 +175,8 @@ def main():
 
     if not args.make_request.startswith('/'):
         for path in os.defpath.split(os.pathsep):
-            if os.path.isfile('/'.join([path, args.make_request])):
-                args.make_request = '/'.join([path, args.make_request])
+            if os.path.isfile(f'{path}/{args.make_request}'):
+                args.make_request = f'{path}/{args.make_request}'
                 break
 
     build_kernels = supported_kernels
diff --git a/ruff.toml b/ruff.toml
new file mode 100644
index 0000000..ac10b23
--- /dev/null
+++ b/ruff.toml
@@ -0,0 +1,6 @@
+# PLD_Builder modules import each other as top-level modules
+src = ["PLD_Builder"]
+
+[lint.per-file-ignores]
+# the package directory name predates PEP 8 and is used in paths
+"PLD_Builder/__init__.py" = ["N999"]
================================================================

---- gitweb:

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



More information about the pld-cvs-commit mailing list