Import the os-release parser from the man page

Fixes https://pagure.io/fedora-rust/rust2rpm/issue/159.

The code in the man page is licensed as CC-0, so it's fine to just
copy it here. (And I wrote it, so it would be fine anyway ;)).
This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2021-11-28 12:48:22 +01:00
parent 1100c60d7b
commit 02a76c3372

View file

@ -1,4 +1,5 @@
import argparse import argparse
import ast
import configparser import configparser
import contextlib import contextlib
from datetime import datetime, timezone from datetime import datetime, timezone
@ -52,26 +53,33 @@ def sortify(func):
return sorted(func(*args, **kwargs)) return sorted(func(*args, **kwargs))
return functools.update_wrapper(wrapper, func) return functools.update_wrapper(wrapper, func)
def get_default_target(): def read_os_release():
try: try:
os_release_file = open('/etc/os-release') f = open('/etc/os-release')
except FileNotFoundError: except FileNotFoundError:
os_release_file = open('/usr/lib/os-release') f = open('/usr/lib/os-release')
with os_release_file:
conf = configparser.ConfigParser() for line in f:
conf.read_file(itertools.chain(["[os-release]"], os_release_file)) line = line.rstrip()
os_release = conf["os-release"] if not line or line.startswith('#'):
continue
m = re.match(r'([A-Z][A-Z_0-9]+)=(.*)', line)
if m:
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") os_id = os_release.get("ID")
os_like = os_release.get("ID_LIKE") # ID_LIKE is a space-separated list of identifiers like ID
if os_like is not None: os_like = os_release.get("ID_LIKE", "").split()
os_like = shlex.split(os_like)
else:
os_like = []
# Order matters here! # Order matters here!
if os_id == "mageia" or ("mageia" in os_like): if "mageia" in (os_id, *os_like):
return "mageia" return "mageia"
elif os_id == "fedora" or ("fedora" in os_like): elif "fedora" in (os_id, *os_like):
return "fedora" return "fedora"
elif "suse" in os_like: elif "suse" in os_like:
return "opensuse" return "opensuse"