]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
Add little helper that combines str.startswith and str.removeprefix 2451/head
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Sat, 2 Mar 2024 11:01:54 +0000 (12:01 +0100)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Tue, 5 Mar 2024 11:04:01 +0000 (12:04 +0100)
This way we don't need to repeat the prefix string.

mkosi/config.py
mkosi/distributions/fedora.py
mkosi/sandbox.py
mkosi/util.py

index 5eaef6b1b27048264067538de522f4ade5e0b80e..d40c39ed492592c210687e0619af8f0e35978a48 100644 (file)
@@ -41,6 +41,7 @@ from mkosi.util import (
     flatten,
     is_power_of_2,
     make_executable,
+    startswith,
 )
 from mkosi.versioncomp import GenericVersion
 
@@ -637,9 +638,11 @@ def config_default_release(namespace: argparse.Namespace) -> str:
 
 def config_default_source_date_epoch(namespace: argparse.Namespace) -> Optional[int]:
     for env in namespace.environment:
-        if env.startswith("SOURCE_DATE_EPOCH="):
-            return config_parse_source_date_epoch(env.removeprefix("SOURCE_DATE_EPOCH="), None)
-    return config_parse_source_date_epoch(os.environ.get("SOURCE_DATE_EPOCH"), None)
+        if s := startswith(env, "SOURCE_DATE_EPOCH="):
+            break
+    else:
+        s = os.environ.get("SOURCE_DATE_EPOCH")
+    return config_parse_source_date_epoch(s, None)
 
 
 def config_default_kernel_command_line(namespace: argparse.Namespace) -> list[str]:
@@ -723,9 +726,9 @@ def config_match_version(match: str, value: str) -> bool:
         ">": operator.gt,
         "<": operator.lt,
     }.items():
-        if match.startswith(sigil):
+        if (rhs := startswith(match, sigil)) is not None:
             op = opfunc
-            comp_version = GenericVersion(match[len(sigil):])
+            comp_version = GenericVersion(rhs)
             break
     else:
         # default to equality if no operation is specified
index 05bea47e4e9813e46496ee8ccf8dcf36ec50f58b..35626af022e37ffa4de12f2a06904451eda48109 100644 (file)
@@ -16,7 +16,7 @@ from mkosi.installer import PackageManager
 from mkosi.installer.dnf import Dnf
 from mkosi.installer.rpm import RpmRepository, find_rpm_gpgkey, setup_rpm
 from mkosi.log import die
-from mkosi.util import listify, tuplify
+from mkosi.util import listify, startswith, tuplify
 
 
 @tuplify
@@ -28,8 +28,8 @@ def find_fedora_rpm_gpgkeys(context: Context) -> Iterable[str]:
         # During branching, there is always a kerfuffle with the key transition.
         # For Rawhide, try to load the N+1 key, just in case our local configuration
         # still indicates that Rawhide==N, but really Rawhide==N+1.
-        if context.config.release == "rawhide" and key1.startswith("file://"):
-            path = Path(key1.removeprefix("file://")).resolve()
+        if context.config.release == "rawhide" and (rhs := startswith(key1, "file://")):
+            path = Path(rhs).resolve()
             if m := re.match(r"RPM-GPG-KEY-fedora-(\d+)-(primary|secondary)", path.name):
                 version = int(m.group(1))
                 if key3 := find_rpm_gpgkey(context, key=f"RPM-GPG-KEY-fedora-{version + 1}-primary"):
index f716effad16332bc068e1c2b6ad48bb758a0c08c..c6098f49030a061f3e75a69914e5947d9e5a2131 100644 (file)
@@ -9,7 +9,7 @@ from typing import Optional, Protocol
 
 from mkosi.types import PathString
 from mkosi.user import INVOKING_USER
-from mkosi.util import flatten, one_zero
+from mkosi.util import flatten, one_zero, startswith
 
 
 class SandboxProtocol(Protocol):
@@ -27,8 +27,8 @@ class Capability(enum.Enum):
 
 def have_effective_cap(capability: Capability) -> bool:
     for line in Path("/proc/self/status").read_text().splitlines():
-        if line.startswith("CapEff:"):
-            hexcap = line.removeprefix("CapEff:").strip()
+        if rhs := startswith(line, "CapEff:"):
+            hexcap = rhs.strip()
             break
     else:
         logging.warning(f"\"CapEff:\" not found in /proc/self/status, assuming we don't have {capability}")
index 38d07608a6fa5ee43cdcf3e0d15d78eacf4a2daa..16c6134551f6064ff87afc528ed624c3e77ff318 100644 (file)
@@ -18,7 +18,7 @@ import tempfile
 from collections.abc import Iterable, Iterator, Mapping, Sequence
 from pathlib import Path
 from types import ModuleType
-from typing import Any, Callable, TypeVar, no_type_check
+from typing import Any, Callable, Optional, TypeVar, no_type_check
 
 from mkosi.types import PathString
 
@@ -59,6 +59,12 @@ def round_up(x: int, blocksize: int = 4096) -> int:
     return (x + blocksize - 1) // blocksize * blocksize
 
 
+def startswith(s: str, prefix: str) -> Optional[str]:
+    if s.startswith(prefix):
+        return s.removeprefix(prefix)
+    return None
+
+
 @dictify
 def read_env_file(path: Path) -> Iterator[tuple[str, str]]:
     with path.open() as f: