Aluode/PerceptionLabPortable
0
1#!/usr/bin/env python2# Copyright 2015-2021 Nir Cohen3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15 16"""17The ``distro`` package (``distro`` stands for Linux Distribution) provides18information about the Linux distribution it runs on, such as a reliable19machine-readable distro ID, or version information.20 21It is the recommended replacement for Python's original22:py:func:`platform.linux_distribution` function, but it provides much more23functionality. An alternative implementation became necessary because Python243.5 deprecated this function, and Python 3.8 removed it altogether. Its25predecessor function :py:func:`platform.dist` was already deprecated since26Python 2.6 and removed in Python 3.8. Still, there are many cases in which27access to OS distribution information is needed. See `Python issue 132228<https://bugs.python.org/issue1322>`_ for more information.29"""30 31import argparse32import json33import logging34import os35import re36import shlex37import subprocess38import sys39import warnings40from typing import (41 Any,42 Callable,43 Dict,44 Iterable,45 Optional,46 Sequence,47 TextIO,48 Tuple,49 Type,50)51 52try:53 from typing import TypedDict54except ImportError:55 # Python 3.756 TypedDict = dict57 58__version__ = "1.9.0"59 60 61class VersionDict(TypedDict):62 major: str63 minor: str64 build_number: str65 66 67class InfoDict(TypedDict):68 id: str69 version: str70 version_parts: VersionDict71 like: str72 codename: str73 74 75_UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc")76_UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib")77_OS_RELEASE_BASENAME = "os-release"78 79#: Translation table for normalizing the "ID" attribute defined in os-release80#: files, for use by the :func:`distro.id` method.81#:82#: * Key: Value as defined in the os-release file, translated to lower case,83#: with blanks translated to underscores.84#:85#: * Value: Normalized value.86NORMALIZED_OS_ID = {87 "ol": "oracle", # Oracle Linux88 "opensuse-leap": "opensuse", # Newer versions of OpenSuSE report as opensuse-leap89}90 91#: Translation table for normalizing the "Distributor ID" attribute returned by92#: the lsb_release command, for use by the :func:`distro.id` method.93#:94#: * Key: Value as returned by the lsb_release command, translated to lower95#: case, with blanks translated to underscores.96#:97#: * Value: Normalized value.98NORMALIZED_LSB_ID = {99 "enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4100 "enterpriseenterpriseserver": "oracle", # Oracle Linux 5101 "redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation102 "redhatenterpriseserver": "rhel", # RHEL 6, 7 Server103 "redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode104}105 106#: Translation table for normalizing the distro ID derived from the file name107#: of distro release files, for use by the :func:`distro.id` method.108#:109#: * Key: Value as derived from the file name of a distro release file,110#: translated to lower case, with blanks translated to underscores.111#:112#: * Value: Normalized value.113NORMALIZED_DISTRO_ID = {114 "redhat": "rhel", # RHEL 6.x, 7.x115}116 117# Pattern for content of distro release file (reversed)118_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(119 r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"120)121 122# Pattern for base file name of distro release file123_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$")124 125# Base file names to be looked up for if _UNIXCONFDIR is not readable.126_DISTRO_RELEASE_BASENAMES = [127 "SuSE-release",128 "altlinux-release",129 "arch-release",130 "base-release",131 "centos-release",132 "fedora-release",133 "gentoo-release",134 "mageia-release",135 "mandrake-release",136 "mandriva-release",137 "mandrivalinux-release",138 "manjaro-release",139 "oracle-release",140 "redhat-release",141 "rocky-release",142 "sl-release",143 "slackware-version",144]145 146# Base file names to be ignored when searching for distro release file147_DISTRO_RELEASE_IGNORE_BASENAMES = (148 "debian_version",149 "lsb-release",150 "oem-release",151 _OS_RELEASE_BASENAME,152 "system-release",153 "plesk-release",154 "iredmail-release",155 "board-release",156 "ec2_version",157)158 159 160def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:161 """162 .. deprecated:: 1.6.0163 164 :func:`distro.linux_distribution()` is deprecated. It should only be165 used as a compatibility shim with Python's166 :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,167 :func:`distro.version` and :func:`distro.name` instead.168 169 Return information about the current OS distribution as a tuple170 ``(id_name, version, codename)`` with items as follows:171 172 * ``id_name``: If *full_distribution_name* is false, the result of173 :func:`distro.id`. Otherwise, the result of :func:`distro.name`.174 175 * ``version``: The result of :func:`distro.version`.176 177 * ``codename``: The extra item (usually in parentheses) after the178 os-release version number, or the result of :func:`distro.codename`.179 180 The interface of this function is compatible with the original181 :py:func:`platform.linux_distribution` function, supporting a subset of182 its parameters.183 184 The data it returns may not exactly be the same, because it uses more data185 sources than the original function, and that may lead to different data if186 the OS distribution is not consistent across multiple data sources it187 provides (there are indeed such distributions ...).188 189 Another reason for differences is the fact that the :func:`distro.id`190 method normalizes the distro ID string to a reliable machine-readable value191 for a number of popular OS distributions.192 """193 warnings.warn(194 "distro.linux_distribution() is deprecated. It should only be used as a "195 "compatibility shim with Python's platform.linux_distribution(). Please use "196 "distro.id(), distro.version() and distro.name() instead.",197 DeprecationWarning,198 stacklevel=2,199 )200 return _distro.linux_distribution(full_distribution_name)201 202 203def id() -> str:204 """205 Return the distro ID of the current distribution, as a206 machine-readable string.207 208 For a number of OS distributions, the returned distro ID value is209 *reliable*, in the sense that it is documented and that it does not change210 across releases of the distribution.211 212 This package maintains the following reliable distro ID values:213 214 ============== =========================================215 Distro ID Distribution216 ============== =========================================217 "ubuntu" Ubuntu218 "debian" Debian219 "rhel" RedHat Enterprise Linux220 "centos" CentOS221 "fedora" Fedora222 "sles" SUSE Linux Enterprise Server223 "opensuse" openSUSE224 "amzn" Amazon Linux225 "arch" Arch Linux226 "buildroot" Buildroot227 "cloudlinux" CloudLinux OS228 "exherbo" Exherbo Linux229 "gentoo" GenToo Linux230 "ibm_powerkvm" IBM PowerKVM231 "kvmibm" KVM for IBM z Systems232 "linuxmint" Linux Mint233 "mageia" Mageia234 "mandriva" Mandriva Linux235 "parallels" Parallels236 "pidora" Pidora237 "raspbian" Raspbian238 "oracle" Oracle Linux (and Oracle Enterprise Linux)239 "scientific" Scientific Linux240 "slackware" Slackware241 "xenserver" XenServer242 "openbsd" OpenBSD243 "netbsd" NetBSD244 "freebsd" FreeBSD245 "midnightbsd" MidnightBSD246 "rocky" Rocky Linux247 "aix" AIX248 "guix" Guix System249 "altlinux" ALT Linux250 ============== =========================================251 252 If you have a need to get distros for reliable IDs added into this set,253 or if you find that the :func:`distro.id` function returns a different254 distro ID for one of the listed distros, please create an issue in the255 `distro issue tracker`_.256 257 **Lookup hierarchy and transformations:**258 259 First, the ID is obtained from the following sources, in the specified260 order. The first available and non-empty value is used:261 262 * the value of the "ID" attribute of the os-release file,263 264 * the value of the "Distributor ID" attribute returned by the lsb_release265 command,266 267 * the first part of the file name of the distro release file,268 269 The so determined ID value then passes the following transformations,270 before it is returned by this method:271 272 * it is translated to lower case,273 274 * blanks (which should not be there anyway) are translated to underscores,275 276 * a normalization of the ID is performed, based upon277 `normalization tables`_. The purpose of this normalization is to ensure278 that the ID is as reliable as possible, even across incompatible changes279 in the OS distributions. A common reason for an incompatible change is280 the addition of an os-release file, or the addition of the lsb_release281 command, with ID values that differ from what was previously determined282 from the distro release file name.283 """284 return _distro.id()285 286 287def name(pretty: bool = False) -> str:288 """289 Return the name of the current OS distribution, as a human-readable290 string.291 292 If *pretty* is false, the name is returned without version or codename.293 (e.g. "CentOS Linux")294 295 If *pretty* is true, the version and codename are appended.296 (e.g. "CentOS Linux 7.1.1503 (Core)")297 298 **Lookup hierarchy:**299 300 The name is obtained from the following sources, in the specified order.301 The first available and non-empty value is used:302 303 * If *pretty* is false:304 305 - the value of the "NAME" attribute of the os-release file,306 307 - the value of the "Distributor ID" attribute returned by the lsb_release308 command,309 310 - the value of the "<name>" field of the distro release file.311 312 * If *pretty* is true:313 314 - the value of the "PRETTY_NAME" attribute of the os-release file,315 316 - the value of the "Description" attribute returned by the lsb_release317 command,318 319 - the value of the "<name>" field of the distro release file, appended320 with the value of the pretty version ("<version_id>" and "<codename>"321 fields) of the distro release file, if available.322 """323 return _distro.name(pretty)324 325 326def version(pretty: bool = False, best: bool = False) -> str:327 """328 Return the version of the current OS distribution, as a human-readable329 string.330 331 If *pretty* is false, the version is returned without codename (e.g.332 "7.0").333 334 If *pretty* is true, the codename in parenthesis is appended, if the335 codename is non-empty (e.g. "7.0 (Maipo)").336 337 Some distributions provide version numbers with different precisions in338 the different sources of distribution information. Examining the different339 sources in a fixed priority order does not always yield the most precise340 version (e.g. for Debian 8.2, or CentOS 7.1).341 342 Some other distributions may not provide this kind of information. In these343 cases, an empty string would be returned. This behavior can be observed344 with rolling releases distributions (e.g. Arch Linux).345 346 The *best* parameter can be used to control the approach for the returned347 version:348 349 If *best* is false, the first non-empty version number in priority order of350 the examined sources is returned.351 352 If *best* is true, the most precise version number out of all examined353 sources is returned.354 355 **Lookup hierarchy:**356 357 In all cases, the version number is obtained from the following sources.358 If *best* is false, this order represents the priority order:359 360 * the value of the "VERSION_ID" attribute of the os-release file,361 * the value of the "Release" attribute returned by the lsb_release362 command,363 * the version number parsed from the "<version_id>" field of the first line364 of the distro release file,365 * the version number parsed from the "PRETTY_NAME" attribute of the366 os-release file, if it follows the format of the distro release files.367 * the version number parsed from the "Description" attribute returned by368 the lsb_release command, if it follows the format of the distro release369 files.370 """371 return _distro.version(pretty, best)372 373 374def version_parts(best: bool = False) -> Tuple[str, str, str]:375 """376 Return the version of the current OS distribution as a tuple377 ``(major, minor, build_number)`` with items as follows:378 379 * ``major``: The result of :func:`distro.major_version`.380 381 * ``minor``: The result of :func:`distro.minor_version`.382 383 * ``build_number``: The result of :func:`distro.build_number`.384 385 For a description of the *best* parameter, see the :func:`distro.version`386 method.387 """388 return _distro.version_parts(best)389 390 391def major_version(best: bool = False) -> str:392 """393 Return the major version of the current OS distribution, as a string,394 if provided.395 Otherwise, the empty string is returned. The major version is the first396 part of the dot-separated version string.397 398 For a description of the *best* parameter, see the :func:`distro.version`399 method.400 """401 return _distro.major_version(best)402 403 404def minor_version(best: bool = False) -> str:405 """406 Return the minor version of the current OS distribution, as a string,407 if provided.408 Otherwise, the empty string is returned. The minor version is the second409 part of the dot-separated version string.410 411 For a description of the *best* parameter, see the :func:`distro.version`412 method.413 """414 return _distro.minor_version(best)415 416 417def build_number(best: bool = False) -> str:418 """419 Return the build number of the current OS distribution, as a string,420 if provided.421 Otherwise, the empty string is returned. The build number is the third part422 of the dot-separated version string.423 424 For a description of the *best* parameter, see the :func:`distro.version`425 method.426 """427 return _distro.build_number(best)428 429 430def like() -> str:431 """432 Return a space-separated list of distro IDs of distributions that are433 closely related to the current OS distribution in regards to packaging434 and programming interfaces, for example distributions the current435 distribution is a derivative from.436 437 **Lookup hierarchy:**438 439 This information item is only provided by the os-release file.440 For details, see the description of the "ID_LIKE" attribute in the441 `os-release man page442 <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.443 """444 return _distro.like()445 446 447def codename() -> str:448 """449 Return the codename for the release of the current OS distribution,450 as a string.451 452 If the distribution does not have a codename, an empty string is returned.453 454 Note that the returned codename is not always really a codename. For455 example, openSUSE returns "x86_64". This function does not handle such456 cases in any special way and just returns the string it finds, if any.457 458 **Lookup hierarchy:**459 460 * the codename within the "VERSION" attribute of the os-release file, if461 provided,462 463 * the value of the "Codename" attribute returned by the lsb_release464 command,465 466 * the value of the "<codename>" field of the distro release file.467 """468 return _distro.codename()469 470 471def info(pretty: bool = False, best: bool = False) -> InfoDict:472 """473 Return certain machine-readable information items about the current OS474 distribution in a dictionary, as shown in the following example:475 476 .. sourcecode:: python477 478 {479 'id': 'rhel',480 'version': '7.0',481 'version_parts': {482 'major': '7',483 'minor': '0',484 'build_number': ''485 },486 'like': 'fedora',487 'codename': 'Maipo'488 }489 490 The dictionary structure and keys are always the same, regardless of which491 information items are available in the underlying data sources. The values492 for the various keys are as follows:493 494 * ``id``: The result of :func:`distro.id`.495 496 * ``version``: The result of :func:`distro.version`.497 498 * ``version_parts -> major``: The result of :func:`distro.major_version`.499 500 * ``version_parts -> minor``: The result of :func:`distro.minor_version`.501 502 * ``version_parts -> build_number``: The result of503 :func:`distro.build_number`.504 505 * ``like``: The result of :func:`distro.like`.506 507 * ``codename``: The result of :func:`distro.codename`.508 509 For a description of the *pretty* and *best* parameters, see the510 :func:`distro.version` method.511 """512 return _distro.info(pretty, best)513 514 515def os_release_info() -> Dict[str, str]:516 """517 Return a dictionary containing key-value pairs for the information items518 from the os-release file data source of the current OS distribution.519 520 See `os-release file`_ for details about these information items.521 """522 return _distro.os_release_info()523 524 525def lsb_release_info() -> Dict[str, str]:526 """527 Return a dictionary containing key-value pairs for the information items528 from the lsb_release command data source of the current OS distribution.529 530 See `lsb_release command output`_ for details about these information531 items.532 """533 return _distro.lsb_release_info()534 535 536def distro_release_info() -> Dict[str, str]:537 """538 Return a dictionary containing key-value pairs for the information items539 from the distro release file data source of the current OS distribution.540 541 See `distro release file`_ for details about these information items.542 """543 return _distro.distro_release_info()544 545 546def uname_info() -> Dict[str, str]:547 """548 Return a dictionary containing key-value pairs for the information items549 from the distro release file data source of the current OS distribution.550 """551 return _distro.uname_info()552 553 554def os_release_attr(attribute: str) -> str:555 """556 Return a single named information item from the os-release file data source557 of the current OS distribution.558 559 Parameters:560 561 * ``attribute`` (string): Key of the information item.562 563 Returns:564 565 * (string): Value of the information item, if the item exists.566 The empty string, if the item does not exist.567 568 See `os-release file`_ for details about these information items.569 """570 return _distro.os_release_attr(attribute)571 572 573def lsb_release_attr(attribute: str) -> str:574 """575 Return a single named information item from the lsb_release command output576 data source of the current OS distribution.577 578 Parameters:579 580 * ``attribute`` (string): Key of the information item.581 582 Returns:583 584 * (string): Value of the information item, if the item exists.585 The empty string, if the item does not exist.586 587 See `lsb_release command output`_ for details about these information588 items.589 """590 return _distro.lsb_release_attr(attribute)591 592 593def distro_release_attr(attribute: str) -> str:594 """595 Return a single named information item from the distro release file596 data source of the current OS distribution.597 598 Parameters:599 600 * ``attribute`` (string): Key of the information item.601 602 Returns:603 604 * (string): Value of the information item, if the item exists.605 The empty string, if the item does not exist.606 607 See `distro release file`_ for details about these information items.608 """609 return _distro.distro_release_attr(attribute)610 611 612def uname_attr(attribute: str) -> str:613 """614 Return a single named information item from the distro release file615 data source of the current OS distribution.616 617 Parameters:618 619 * ``attribute`` (string): Key of the information item.620 621 Returns:622 623 * (string): Value of the information item, if the item exists.624 The empty string, if the item does not exist.625 """626 return _distro.uname_attr(attribute)627 628 629try:630 from functools import cached_property631except ImportError:632 # Python < 3.8633 class cached_property: # type: ignore634 """A version of @property which caches the value. On access, it calls the635 underlying function and sets the value in `__dict__` so future accesses636 will not re-call the property.637 """638 639 def __init__(self, f: Callable[[Any], Any]) -> None:640 self._fname = f.__name__641 self._f = f642 643 def __get__(self, obj: Any, owner: Type[Any]) -> Any:644 assert obj is not None, f"call {self._fname} on an instance"645 ret = obj.__dict__[self._fname] = self._f(obj)646 return ret647 648 649class LinuxDistribution:650 """651 Provides information about a OS distribution.652 653 This package creates a private module-global instance of this class with654 default initialization arguments, that is used by the655 `consolidated accessor functions`_ and `single source accessor functions`_.656 By using default initialization arguments, that module-global instance657 returns data about the current OS distribution (i.e. the distro this658 package runs on).659 660 Normally, it is not necessary to create additional instances of this class.661 However, in situations where control is needed over the exact data sources662 that are used, instances of this class can be created with a specific663 distro release file, or a specific os-release file, or without invoking the664 lsb_release command.665 """666 667 def __init__(668 self,669 include_lsb: Optional[bool] = None,670 os_release_file: str = "",671 distro_release_file: str = "",672 include_uname: Optional[bool] = None,673 root_dir: Optional[str] = None,674 include_oslevel: Optional[bool] = None,675 ) -> None:676 """677 The initialization method of this class gathers information from the678 available data sources, and stores that in private instance attributes.679 Subsequent access to the information items uses these private instance680 attributes, so that the data sources are read only once.681 682 Parameters:683 684 * ``include_lsb`` (bool): Controls whether the685 `lsb_release command output`_ is included as a data source.686 687 If the lsb_release command is not available in the program execution688 path, the data source for the lsb_release command will be empty.689 690 * ``os_release_file`` (string): The path name of the691 `os-release file`_ that is to be used as a data source.692 693 An empty string (the default) will cause the default path name to694 be used (see `os-release file`_ for details).695 696 If the specified or defaulted os-release file does not exist, the697 data source for the os-release file will be empty.698 699 * ``distro_release_file`` (string): The path name of the700 `distro release file`_ that is to be used as a data source.701 702 An empty string (the default) will cause a default search algorithm703 to be used (see `distro release file`_ for details).704 705 If the specified distro release file does not exist, or if no default706 distro release file can be found, the data source for the distro707 release file will be empty.708 709 * ``include_uname`` (bool): Controls whether uname command output is710 included as a data source. If the uname command is not available in711 the program execution path the data source for the uname command will712 be empty.713 714 * ``root_dir`` (string): The absolute path to the root directory to use715 to find distro-related information files. Note that ``include_*``716 parameters must not be enabled in combination with ``root_dir``.717 718 * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command719 output is included as a data source. If the oslevel command is not720 available in the program execution path the data source will be721 empty.722 723 Public instance attributes:724 725 * ``os_release_file`` (string): The path name of the726 `os-release file`_ that is actually used as a data source. The727 empty string if no distro release file is used as a data source.728 729 * ``distro_release_file`` (string): The path name of the730 `distro release file`_ that is actually used as a data source. The731 empty string if no distro release file is used as a data source.732 733 * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.734 This controls whether the lsb information will be loaded.735 736 * ``include_uname`` (bool): The result of the ``include_uname``737 parameter. This controls whether the uname information will738 be loaded.739 740 * ``include_oslevel`` (bool): The result of the ``include_oslevel``741 parameter. This controls whether (AIX) oslevel information will be742 loaded.743 744 * ``root_dir`` (string): The result of the ``root_dir`` parameter.745 The absolute path to the root directory to use to find distro-related746 information files.747 748 Raises:749 750 * :py:exc:`ValueError`: Initialization parameters combination is not751 supported.752 753 * :py:exc:`OSError`: Some I/O issue with an os-release file or distro754 release file.755 756 * :py:exc:`UnicodeError`: A data source has unexpected characters or757 uses an unexpected encoding.758 """759 self.root_dir = root_dir760 self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR761 self.usr_lib_dir = (762 os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR763 )764 765 if os_release_file:766 self.os_release_file = os_release_file767 else:768 etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)769 usr_lib_os_release_file = os.path.join(770 self.usr_lib_dir, _OS_RELEASE_BASENAME771 )772 773 # NOTE: The idea is to respect order **and** have it set774 # at all times for API backwards compatibility.775 if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(776 usr_lib_os_release_file777 ):778 self.os_release_file = etc_dir_os_release_file779 else:780 self.os_release_file = usr_lib_os_release_file781 782 self.distro_release_file = distro_release_file or "" # updated later783 784 is_root_dir_defined = root_dir is not None785 if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):786 raise ValueError(787 "Including subprocess data sources from specific root_dir is disallowed"788 " to prevent false information"789 )790 self.include_lsb = (791 include_lsb if include_lsb is not None else not is_root_dir_defined792 )793 self.include_uname = (794 include_uname if include_uname is not None else not is_root_dir_defined795 )796 self.include_oslevel = (797 include_oslevel if include_oslevel is not None else not is_root_dir_defined798 )799 800 def __repr__(self) -> str:801 """Return repr of all info"""802 return (803 "LinuxDistribution("804 "os_release_file={self.os_release_file!r}, "805 "distro_release_file={self.distro_release_file!r}, "806 "include_lsb={self.include_lsb!r}, "807 "include_uname={self.include_uname!r}, "808 "include_oslevel={self.include_oslevel!r}, "809 "root_dir={self.root_dir!r}, "810 "_os_release_info={self._os_release_info!r}, "811 "_lsb_release_info={self._lsb_release_info!r}, "812 "_distro_release_info={self._distro_release_info!r}, "813 "_uname_info={self._uname_info!r}, "814 "_oslevel_info={self._oslevel_info!r})".format(self=self)815 )816 817 def linux_distribution(818 self, full_distribution_name: bool = True819 ) -> Tuple[str, str, str]:820 """821 Return information about the OS distribution that is compatible822 with Python's :func:`platform.linux_distribution`, supporting a subset823 of its parameters.824 825 For details, see :func:`distro.linux_distribution`.826 """827 return (828 self.name() if full_distribution_name else self.id(),829 self.version(),830 self._os_release_info.get("release_codename") or self.codename(),831 )832 833 def id(self) -> str:834 """Return the distro ID of the OS distribution, as a string.835 836 For details, see :func:`distro.id`.837 """838 839 def normalize(distro_id: str, table: Dict[str, str]) -> str:840 distro_id = distro_id.lower().replace(" ", "_")841 return table.get(distro_id, distro_id)842 843 distro_id = self.os_release_attr("id")844 if distro_id:845 return normalize(distro_id, NORMALIZED_OS_ID)846 847 distro_id = self.lsb_release_attr("distributor_id")848 if distro_id:849 return normalize(distro_id, NORMALIZED_LSB_ID)850 851 distro_id = self.distro_release_attr("id")852 if distro_id:853 return normalize(distro_id, NORMALIZED_DISTRO_ID)854 855 distro_id = self.uname_attr("id")856 if distro_id:857 return normalize(distro_id, NORMALIZED_DISTRO_ID)858 859 return ""860 861 def name(self, pretty: bool = False) -> str:862 """863 Return the name of the OS distribution, as a string.864 865 For details, see :func:`distro.name`.866 """867 name = (868 self.os_release_attr("name")869 or self.lsb_release_attr("distributor_id")870 or self.distro_release_attr("name")871 or self.uname_attr("name")872 )873 if pretty:874 name = self.os_release_attr("pretty_name") or self.lsb_release_attr(875 "description"876 )877 if not name:878 name = self.distro_release_attr("name") or self.uname_attr("name")879 version = self.version(pretty=True)880 if version:881 name = f"{name} {version}"882 return name or ""883 884 def version(self, pretty: bool = False, best: bool = False) -> str:885 """886 Return the version of the OS distribution, as a string.887 888 For details, see :func:`distro.version`.889 """890 versions = [891 self.os_release_attr("version_id"),892 self.lsb_release_attr("release"),893 self.distro_release_attr("version_id"),894 self._parse_distro_release_content(self.os_release_attr("pretty_name")).get(895 "version_id", ""896 ),897 self._parse_distro_release_content(898 self.lsb_release_attr("description")899 ).get("version_id", ""),900 self.uname_attr("release"),901 ]902 if self.uname_attr("id").startswith("aix"):903 # On AIX platforms, prefer oslevel command output.904 versions.insert(0, self.oslevel_info())905 elif self.id() == "debian" or "debian" in self.like().split():906 # On Debian-like, add debian_version file content to candidates list.907 versions.append(self._debian_version)908 version = ""909 if best:910 # This algorithm uses the last version in priority order that has911 # the best precision. If the versions are not in conflict, that912 # does not matter; otherwise, using the last one instead of the913 # first one might be considered a surprise.914 for v in versions:915 if v.count(".") > version.count(".") or version == "":916 version = v917 else:918 for v in versions:919 if v != "":920 version = v921 break922 if pretty and version and self.codename():923 version = f"{version} ({self.codename()})"924 return version925 926 def version_parts(self, best: bool = False) -> Tuple[str, str, str]:927 """928 Return the version of the OS distribution, as a tuple of version929 numbers.930 931 For details, see :func:`distro.version_parts`.932 """933 version_str = self.version(best=best)934 if version_str:935 version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?")936 matches = version_regex.match(version_str)937 if matches:938 major, minor, build_number = matches.groups()939 return major, minor or "", build_number or ""940 return "", "", ""941 942 def major_version(self, best: bool = False) -> str:943 """944 Return the major version number of the current distribution.945 946 For details, see :func:`distro.major_version`.947 """948 return self.version_parts(best)[0]949 950 def minor_version(self, best: bool = False) -> str:951 """952 Return the minor version number of the current distribution.953 954 For details, see :func:`distro.minor_version`.955 """956 return self.version_parts(best)[1]957 958 def build_number(self, best: bool = False) -> str:959 """960 Return the build number of the current distribution.961 962 For details, see :func:`distro.build_number`.963 """964 return self.version_parts(best)[2]965 966 def like(self) -> str:967 """968 Return the IDs of distributions that are like the OS distribution.969 970 For details, see :func:`distro.like`.971 """972 return self.os_release_attr("id_like") or ""973 974 def codename(self) -> str:975 """976 Return the codename of the OS distribution.977 978 For details, see :func:`distro.codename`.979 """980 try:981 # Handle os_release specially since distros might purposefully set982 # this to empty string to have no codename983 return self._os_release_info["codename"]984 except KeyError:985 return (986 self.lsb_release_attr("codename")987 or self.distro_release_attr("codename")988 or ""989 )990 991 def info(self, pretty: bool = False, best: bool = False) -> InfoDict:992 """993 Return certain machine-readable information about the OS994 distribution.995 996 For details, see :func:`distro.info`.997 """998 return InfoDict(999 id=self.id(),1000 version=self.version(pretty, best),1001 version_parts=VersionDict(1002 major=self.major_version(best),1003 minor=self.minor_version(best),1004 build_number=self.build_number(best),1005 ),1006 like=self.like(),1007 codename=self.codename(),1008 )1009 1010 def os_release_info(self) -> Dict[str, str]:1011 """1012 Return a dictionary containing key-value pairs for the information1013 items from the os-release file data source of the OS distribution.1014 1015 For details, see :func:`distro.os_release_info`.1016 """1017 return self._os_release_info1018 1019 def lsb_release_info(self) -> Dict[str, str]:1020 """1021 Return a dictionary containing key-value pairs for the information1022 items from the lsb_release command data source of the OS1023 distribution.1024 1025 For details, see :func:`distro.lsb_release_info`.1026 """1027 return self._lsb_release_info1028 1029 def distro_release_info(self) -> Dict[str, str]:1030 """1031 Return a dictionary containing key-value pairs for the information1032 items from the distro release file data source of the OS1033 distribution.1034 1035 For details, see :func:`distro.distro_release_info`.1036 """1037 return self._distro_release_info1038 1039 def uname_info(self) -> Dict[str, str]:1040 """1041 Return a dictionary containing key-value pairs for the information1042 items from the uname command data source of the OS distribution.1043 1044 For details, see :func:`distro.uname_info`.1045 """1046 return self._uname_info1047 1048 def oslevel_info(self) -> str:1049 """1050 Return AIX' oslevel command output.1051 """1052 return self._oslevel_info1053 1054 def os_release_attr(self, attribute: str) -> str:1055 """1056 Return a single named information item from the os-release file data1057 source of the OS distribution.1058 1059 For details, see :func:`distro.os_release_attr`.1060 """1061 return self._os_release_info.get(attribute, "")1062 1063 def lsb_release_attr(self, attribute: str) -> str:1064 """1065 Return a single named information item from the lsb_release command1066 output data source of the OS distribution.1067 1068 For details, see :func:`distro.lsb_release_attr`.1069 """1070 return self._lsb_release_info.get(attribute, "")1071 1072 def distro_release_attr(self, attribute: str) -> str:1073 """1074 Return a single named information item from the distro release file1075 data source of the OS distribution.1076 1077 For details, see :func:`distro.distro_release_attr`.1078 """1079 return self._distro_release_info.get(attribute, "")1080 1081 def uname_attr(self, attribute: str) -> str:1082 """1083 Return a single named information item from the uname command1084 output data source of the OS distribution.1085 1086 For details, see :func:`distro.uname_attr`.1087 """1088 return self._uname_info.get(attribute, "")1089 1090 @cached_property1091 def _os_release_info(self) -> Dict[str, str]:1092 """1093 Get the information items from the specified os-release file.1094 1095 Returns:1096 A dictionary containing all information items.1097 """1098 if os.path.isfile(self.os_release_file):1099 with open(self.os_release_file, encoding="utf-8") as release_file:1100 return self._parse_os_release_content(release_file)1101 return {}1102 1103 @staticmethod1104 def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:1105 """1106 Parse the lines of an os-release file.1107 1108 Parameters:1109 1110 * lines: Iterable through the lines in the os-release file.1111 Each line must be a unicode string or a UTF-8 encoded byte1112 string.1113 1114 Returns:1115 A dictionary containing all information items.1116 """1117 props = {}1118 lexer = shlex.shlex(lines, posix=True)1119 lexer.whitespace_split = True1120 1121 tokens = list(lexer)1122 for token in tokens:1123 # At this point, all shell-like parsing has been done (i.e.1124 # comments processed, quotes and backslash escape sequences1125 # processed, multi-line values assembled, trailing newlines1126 # stripped, etc.), so the tokens are now either:1127 # * variable assignments: var=value1128 # * commands or their arguments (not allowed in os-release)1129 # Ignore any tokens that are not variable assignments1130 if "=" in token:1131 k, v = token.split("=", 1)1132 props[k.lower()] = v1133 1134 if "version" in props:1135 # extract release codename (if any) from version attribute1136 match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"])1137 if match:1138 release_codename = match.group(1) or match.group(2)1139 props["codename"] = props["release_codename"] = release_codename1140 1141 if "version_codename" in props:1142 # os-release added a version_codename field. Use that in1143 # preference to anything else Note that some distros purposefully1144 # do not have code names. They should be setting1145 # version_codename=""1146 props["codename"] = props["version_codename"]1147 elif "ubuntu_codename" in props:1148 # Same as above but a non-standard field name used on older Ubuntus1149 props["codename"] = props["ubuntu_codename"]1150 1151 return props1152 1153 @cached_property1154 def _lsb_release_info(self) -> Dict[str, str]:1155 """1156 Get the information items from the lsb_release command output.1157 1158 Returns:1159 A dictionary containing all information items.1160 """1161 if not self.include_lsb:1162 return {}1163 try:1164 cmd = ("lsb_release", "-a")1165 stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)1166 # Command not found or lsb_release returned error1167 except (OSError, subprocess.CalledProcessError):1168 return {}1169 content = self._to_str(stdout).splitlines()1170 return self._parse_lsb_release_content(content)1171 1172 @staticmethod1173 def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:1174 """1175 Parse the output of the lsb_release command.1176 1177 Parameters:1178 1179 * lines: Iterable through the lines of the lsb_release output.1180 Each line must be a unicode string or a UTF-8 encoded byte1181 string.1182 1183 Returns:1184 A dictionary containing all information items.1185 """1186 props = {}1187 for line in lines:1188 kv = line.strip("\n").split(":", 1)1189 if len(kv) != 2:1190 # Ignore lines without colon.1191 continue1192 k, v = kv1193 props.update({k.replace(" ", "_").lower(): v.strip()})1194 return props1195 1196 @cached_property1197 def _uname_info(self) -> Dict[str, str]:1198 if not self.include_uname:1199 return {}1200 try: