python-distro / distro

A much more elaborate replacement for removed Python's `platform.linux_distribution()` method
https://distro.readthedocs.io/
Apache License 2.0
265 stars 66 forks source link

Drastically lowers `LinuxDistribution._distro_release_info` complexity #327

Closed HorlogeSkynet closed 2 years ago

HorlogeSkynet commented 2 years ago

@hartwork This is the diff I've just amended, to simplify your review :innocent:

More simplifications, and your documentation-related ideas.

diff --git a/src/distro/distro.py b/src/distro/distro.py
index 8209256..4d08067 100755
--- a/src/distro/distro.py
+++ b/src/distro/distro.py
@@ -1250,7 +1250,12 @@ class LinuxDistribution:
             match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
         else:
             try:
-                basenames = os.listdir(self.etc_dir)
+                basenames = [
+                    basename
+                    for basename in os.listdir(self.etc_dir)
+                    if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES
+                    and os.path.isfile(os.path.join(self.etc_dir, basename))
+                ]
                 # We sort for repeatability in cases where there are multiple
                 # distro specific files; e.g. CentOS, Oracle, Enterprise all
                 # containing `redhat-release` on top of their own.
@@ -1262,10 +1267,8 @@ class LinuxDistribution:
                 # error is handled in `_parse_distro_release_file()`.
                 basenames = _DISTRO_RELEASE_BASENAMES
             for basename in basenames:
-                if basename in _DISTRO_RELEASE_IGNORE_BASENAMES:
-                    continue
                 match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
-                if not match:
+                if match is None:
                     continue
                 filepath = os.path.join(self.etc_dir, basename)
                 distro_info = self._parse_distro_release_file(filepath)
@@ -1274,13 +1277,13 @@ class LinuxDistribution:
                     continue
                 self.distro_release_file = filepath
                 break
-            else:
+            else:  # the loop didn't "break": no candidate.
                 return {}

         if match is not None:
             distro_info["id"] = match.group(1)

-        # manually set id for CloudLinux
+        # CloudLinux < 7: manually enrich info with proper id.
         if "cloudlinux" in distro_info.get("name", "").lower():
             distro_info["id"] = "cloudlinux"