Skip to content

Commit

Permalink
Cache /etc/debian_version content (#349)
Browse files Browse the repository at this point in the history
This patch is a follow-up for 6d44662 (#333), introducing caching of `/etc/debian_version` file content, to prevent opening and reading operations for each `distro.version()` call.
  • Loading branch information
HorlogeSkynet authored Oct 10, 2022
1 parent 095882f commit 8be3ae6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
18 changes: 11 additions & 7 deletions src/distro/distro.py
Original file line number Diff line number Diff line change
Expand Up @@ -900,13 +900,7 @@ def version(self, pretty: bool = False, best: bool = False) -> str:
versions.insert(0, self.oslevel_info())
elif self.id() == "debian" or "debian" in self.like().split():
# On Debian-like, add debian_version file content to candidates list.
try:
with open(
os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
) as fp:
versions.append(fp.readline().rstrip())
except FileNotFoundError:
pass
versions.append(self._debian_version)
version = ""
if best:
# This algorithm uses the last version in priority order that has
Expand Down Expand Up @@ -1217,6 +1211,16 @@ def _oslevel_info(self) -> str:
return ""
return self._to_str(stdout).strip()

@cached_property
def _debian_version(self) -> str:
try:
with open(
os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
) as fp:
return fp.readline().rstrip()
except FileNotFoundError:
return ""

@staticmethod
def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:
if not lines:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_distro.py
Original file line number Diff line number Diff line change
Expand Up @@ -2272,6 +2272,6 @@ def test_repr(self) -> None:
repr_str = repr(distro._distro)
assert "LinuxDistribution" in repr_str
for attr in MODULE_DISTRO.__dict__.keys():
if attr in ("root_dir", "etc_dir", "usr_lib_dir"):
if attr in ("root_dir", "etc_dir", "usr_lib_dir", "_debian_version"):
continue
assert f"{attr}=" in repr_str

0 comments on commit 8be3ae6

Please sign in to comment.