From 0f2e5ab6f22b96c0c6257d088057b4f6076b7adb Mon Sep 17 00:00:00 2001 From: Fabio Valentini Date: Mon, 13 Feb 2023 19:50:17 +0100 Subject: [PATCH] sysinfo: move os-release parsing into separate module Any opened files are now also closed after reading them. --- rust2rpm/__main__.py | 35 +---------------------------------- rust2rpm/sysinfo.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 34 deletions(-) create mode 100644 rust2rpm/sysinfo.py diff --git a/rust2rpm/__main__.py b/rust2rpm/__main__.py index 04367a2..573a4fc 100644 --- a/rust2rpm/__main__.py +++ b/rust2rpm/__main__.py @@ -19,6 +19,7 @@ from . import cfg, licensing, generator, log, util from .core.metadata import Metadata from .cratesio import download_crate, NoVersionsError from .distgit import get_package_info +from .sysinfo import get_default_target LICENSES = re.compile( @@ -58,40 +59,6 @@ def sortify(func): return functools.update_wrapper(wrapper, func) -def read_os_release(): - try: - f = open("/etc/os-release") - except FileNotFoundError: - f = open("/usr/lib/os-release") - - for line in f: - line = line.rstrip() - if not line or line.startswith("#"): - continue - if m := re.match(r"([A-Z][A-Z_0-9]+)=(.*)", line): - name, val = m.groups() - if val and val[0] in "\"'": - val = ast.literal_eval(val) - yield name, val - - -def get_default_target(): - os_release = dict(read_os_release()) - os_id = os_release.get("ID") - # ID_LIKE is a space-separated list of identifiers like ID - os_like = os_release.get("ID_LIKE", "").split() - - # Order matters here! - if "mageia" in (os_id, *os_like): - return "mageia" - elif "fedora" in (os_id, *os_like): - return "fedora" - elif "suse" in os_like: - return "opensuse" - else: - return "plain" - - def file_mtime(path): return datetime.fromtimestamp(os.stat(path).st_mtime, timezone.utc).isoformat() diff --git a/rust2rpm/sysinfo.py b/rust2rpm/sysinfo.py new file mode 100644 index 0000000..4443308 --- /dev/null +++ b/rust2rpm/sysinfo.py @@ -0,0 +1,43 @@ +import ast +import re + + +def read_os_release() -> dict[str, str]: + try: + with open("/etc/os-release") as file: + contents = file.read() + except FileNotFoundError: + with open("/usr/lib/os-release") as file: + contents = file.read() + + data = dict() + + for line in contents.splitlines(): + line = line.rstrip() + if not line or line.startswith("#"): + continue + if m := re.match(r"([A-Z][A-Z_0-9]+)=(.*)", line): + name, val = m.groups() + if val and val[0] in "\"'": + val = ast.literal_eval(val) + data[name] = val + + return data + + +def get_default_target() -> str: + os_release = read_os_release() + os_id = os_release.get("ID") + + # ID_LIKE is a space-separated list of identifiers like ID + os_like = os_release.get("ID_LIKE", "").split() + + # Order matters here! + if "mageia" in (os_id, *os_like): + return "mageia" + elif "fedora" in (os_id, *os_like): + return "fedora" + elif "suse" in os_like: + return "opensuse" + else: + return "plain"