Coverage for rust2rpm/sysinfo.py: 75%

41 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2024-11-22 22:41 +0100

1"""Module containing functionality for determining the default `Target` from the current system.""" 

2 

3import ast 

4import re 

5from enum import StrEnum 

6from pathlib import Path 

7 

8 

9class Target(StrEnum): 

10 """Target for generated spec files.""" 

11 

12 FEDORA = "fedora" 

13 OPENSUSE = "opensuse" 

14 EPEL8 = "epel8" 

15 MAGEIA = "mageia" 

16 PLAIN = "plain" 

17 """Target for build environments with minimal RPM macros but no dependency generators.""" 

18 

19 

20TARGET_NAMES = [target.value for target in Target] 

21 

22 

23def read_os_release() -> dict[str, str]: 

24 """Return parsed contents of the os-release file. 

25 

26 Returns: 

27 Mapping from keys to values. 

28 

29 """ 

30 try: 

31 with Path("/etc/os-release").open() as file: 

32 contents = file.read() 

33 except FileNotFoundError: 

34 with Path("/usr/lib/os-release").open() as file: 

35 contents = file.read() 

36 

37 data = {} 

38 

39 for line in contents.splitlines(): 

40 stripped = line.rstrip() 

41 if not stripped or stripped.startswith("#"): 41 ↛ 42line 41 didn't jump to line 42 because the condition on line 41 was never true

42 continue 

43 if m := re.match(r"([A-Z][A-Z_0-9]+)=(.*)", stripped): 43 ↛ 39line 43 didn't jump to line 39 because the condition on line 43 was always true

44 name, val = m.groups() 

45 if val and val[0] in "\"'": 

46 val = ast.literal_eval(val) 

47 data[name] = val 

48 

49 return data 

50 

51 

52def get_default_target() -> Target: 

53 """Return default `Target` based on the current system. 

54 

55 Returns: 

56 Default target for the current system. 

57 

58 """ 

59 os_release = read_os_release() 

60 os_id = os_release.get("ID") 

61 

62 # ID_LIKE is a space-separated list of identifiers like ID 

63 os_like = os_release.get("ID_LIKE", "").split() 

64 

65 # Order matters here! 

66 if "mageia" in (os_id, *os_like): 66 ↛ 67line 66 didn't jump to line 67 because the condition on line 66 was never true

67 return Target.MAGEIA 

68 if "fedora" in (os_id, *os_like): 68 ↛ 70line 68 didn't jump to line 70 because the condition on line 68 was always true

69 return Target.FEDORA 

70 if "suse" in os_like: 

71 return Target.OPENSUSE 

72 return Target.PLAIN