[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-04-13 00:00:18 +00:00
parent 72ad6dc953
commit f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions

View file

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The ``distro`` package (``distro`` stands for Linux Distribution) provides
information about the Linux distribution it runs on, such as a reliable
@ -26,6 +25,7 @@ Python 2.6 and removed in Python 3.8. Still, there are many cases in which
access to OS distribution information is needed. See `Python issue 1322
<https://bugs.python.org/issue1322>`_ for more information.
"""
from __future__ import annotations
import argparse
import json
@ -37,7 +37,7 @@ import subprocess
import sys
import warnings
__version__ = "1.6.0"
__version__ = '1.6.0'
# Use `if False` to avoid an ImportError on Python 2. After dropping Python 2
# support, can use typing.TYPE_CHECKING instead. See:
@ -57,24 +57,22 @@ if False: # pragma: nocover
Union,
)
VersionDict = TypedDict(
"VersionDict", {"major": str, "minor": str, "build_number": str}
)
InfoDict = TypedDict(
"InfoDict",
{
"id": str,
"version": str,
"version_parts": VersionDict,
"like": str,
"codename": str,
},
)
class VersionDict(TypedDict):
major: str
minor: str
build_number: str
class InfoDict(TypedDict):
id: str
version: str
version_parts: VersionDict
like: str
codename: str
_UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc")
_UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib")
_OS_RELEASE_BASENAME = "os-release"
_UNIXCONFDIR = os.environ.get('UNIXCONFDIR', '/etc')
_UNIXUSRLIBDIR = os.environ.get('UNIXUSRLIBDIR', '/usr/lib')
_OS_RELEASE_BASENAME = 'os-release'
#: Translation table for normalizing the "ID" attribute defined in os-release
#: files, for use by the :func:`distro.id` method.
@ -84,7 +82,7 @@ _OS_RELEASE_BASENAME = "os-release"
#:
#: * Value: Normalized value.
NORMALIZED_OS_ID = {
"ol": "oracle", # Oracle Linux
'ol': 'oracle', # Oracle Linux
}
#: Translation table for normalizing the "Distributor ID" attribute returned by
@ -95,11 +93,11 @@ NORMALIZED_OS_ID = {
#:
#: * Value: Normalized value.
NORMALIZED_LSB_ID = {
"enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4
"enterpriseenterpriseserver": "oracle", # Oracle Linux 5
"redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation
"redhatenterpriseserver": "rhel", # RHEL 6, 7 Server
"redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode
'enterpriseenterpriseas': 'oracle', # Oracle Enterprise Linux 4
'enterpriseenterpriseserver': 'oracle', # Oracle Linux 5
'redhatenterpriseworkstation': 'rhel', # RHEL 6, 7 Workstation
'redhatenterpriseserver': 'rhel', # RHEL 6, 7 Server
'redhatenterprisecomputenode': 'rhel', # RHEL 6 ComputeNode
}
#: Translation table for normalizing the distro ID derived from the file name
@ -110,26 +108,26 @@ NORMALIZED_LSB_ID = {
#:
#: * Value: Normalized value.
NORMALIZED_DISTRO_ID = {
"redhat": "rhel", # RHEL 6.x, 7.x
'redhat': 'rhel', # RHEL 6.x, 7.x
}
# Pattern for content of distro release file (reversed)
_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"
r'(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)',
)
# Pattern for base file name of distro release file
_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$")
_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r'(\w+)[-_](release|version)$')
# Base file names to be ignored when searching for distro release file
_DISTRO_RELEASE_IGNORE_BASENAMES = (
"debian_version",
"lsb-release",
"oem-release",
'debian_version',
'lsb-release',
'oem-release',
_OS_RELEASE_BASENAME,
"system-release",
"plesk-release",
"iredmail-release",
'system-release',
'plesk-release',
'iredmail-release',
)
@ -167,9 +165,9 @@ def linux_distribution(full_distribution_name=True):
for a number of popular OS distributions.
"""
warnings.warn(
"distro.linux_distribution() is deprecated. It should only be used as a "
'distro.linux_distribution() is deprecated. It should only be used as a '
"compatibility shim with Python's platform.linux_distribution(). Please use "
"distro.id(), distro.version() and distro.name() instead.",
'distro.id(), distro.version() and distro.name() instead.',
DeprecationWarning,
stacklevel=2,
)
@ -615,7 +613,7 @@ try:
from functools import cached_property
except ImportError:
# Python < 3.8
class cached_property(object): # type: ignore
class cached_property: # type: ignore
"""A version of @property which caches the value. On access, it calls the
underlying function and sets the value in `__dict__` so future accesses
will not re-call the property.
@ -628,12 +626,12 @@ except ImportError:
def __get__(self, obj, owner):
# type: (Any, Type[Any]) -> Any
assert obj is not None, "call {} on an instance".format(self._fname)
assert obj is not None, f'call {self._fname} on an instance'
ret = obj.__dict__[self._fname] = self._f(obj)
return ret
class LinuxDistribution(object):
class LinuxDistribution:
"""
Provides information about a OS distribution.
@ -654,8 +652,8 @@ class LinuxDistribution(object):
def __init__(
self,
include_lsb=True,
os_release_file="",
distro_release_file="",
os_release_file='',
distro_release_file='',
include_uname=True,
root_dir=None,
):
@ -731,9 +729,9 @@ class LinuxDistribution(object):
uses an unexpected encoding.
"""
self.root_dir = root_dir
self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR
self.etc_dir = os.path.join(root_dir, 'etc') if root_dir else _UNIXCONFDIR
self.usr_lib_dir = (
os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR
os.path.join(root_dir, 'usr/lib') if root_dir else _UNIXUSRLIBDIR
)
if os_release_file:
@ -741,19 +739,19 @@ class LinuxDistribution(object):
else:
etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)
usr_lib_os_release_file = os.path.join(
self.usr_lib_dir, _OS_RELEASE_BASENAME
self.usr_lib_dir, _OS_RELEASE_BASENAME,
)
# NOTE: The idea is to respect order **and** have it set
# at all times for API backwards compatibility.
if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(
usr_lib_os_release_file
usr_lib_os_release_file,
):
self.os_release_file = etc_dir_os_release_file
else:
self.os_release_file = usr_lib_os_release_file
self.distro_release_file = distro_release_file or "" # updated later
self.distro_release_file = distro_release_file or '' # updated later
self.include_lsb = include_lsb
self.include_uname = include_uname
@ -761,15 +759,15 @@ class LinuxDistribution(object):
# type: () -> str
"""Return repr of all info"""
return (
"LinuxDistribution("
"os_release_file={self.os_release_file!r}, "
"distro_release_file={self.distro_release_file!r}, "
"include_lsb={self.include_lsb!r}, "
"include_uname={self.include_uname!r}, "
"_os_release_info={self._os_release_info!r}, "
"_lsb_release_info={self._lsb_release_info!r}, "
"_distro_release_info={self._distro_release_info!r}, "
"_uname_info={self._uname_info!r})".format(self=self)
'LinuxDistribution('
'os_release_file={self.os_release_file!r}, '
'distro_release_file={self.distro_release_file!r}, '
'include_lsb={self.include_lsb!r}, '
'include_uname={self.include_uname!r}, '
'_os_release_info={self._os_release_info!r}, '
'_lsb_release_info={self._lsb_release_info!r}, '
'_distro_release_info={self._distro_release_info!r}, '
'_uname_info={self._uname_info!r})'.format(self=self)
)
def linux_distribution(self, full_distribution_name=True):
@ -796,26 +794,26 @@ class LinuxDistribution(object):
def normalize(distro_id, table):
# type: (str, Dict[str, str]) -> str
distro_id = distro_id.lower().replace(" ", "_")
distro_id = distro_id.lower().replace(' ', '_')
return table.get(distro_id, distro_id)
distro_id = self.os_release_attr("id")
distro_id = self.os_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_OS_ID)
distro_id = self.lsb_release_attr("distributor_id")
distro_id = self.lsb_release_attr('distributor_id')
if distro_id:
return normalize(distro_id, NORMALIZED_LSB_ID)
distro_id = self.distro_release_attr("id")
distro_id = self.distro_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
distro_id = self.uname_attr("id")
distro_id = self.uname_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
return ""
return ''
def name(self, pretty=False):
# type: (bool) -> str
@ -825,21 +823,21 @@ class LinuxDistribution(object):
For details, see :func:`distro.name`.
"""
name = (
self.os_release_attr("name")
or self.lsb_release_attr("distributor_id")
or self.distro_release_attr("name")
or self.uname_attr("name")
self.os_release_attr('name') or
self.lsb_release_attr('distributor_id') or
self.distro_release_attr('name') or
self.uname_attr('name')
)
if pretty:
name = self.os_release_attr("pretty_name") or self.lsb_release_attr(
"description"
name = self.os_release_attr('pretty_name') or self.lsb_release_attr(
'description',
)
if not name:
name = self.distro_release_attr("name") or self.uname_attr("name")
name = self.distro_release_attr('name') or self.uname_attr('name')
version = self.version(pretty=True)
if version:
name = name + " " + version
return name or ""
name = name + ' ' + version
return name or ''
def version(self, pretty=False, best=False):
# type: (bool, bool) -> str
@ -849,33 +847,33 @@ class LinuxDistribution(object):
For details, see :func:`distro.version`.
"""
versions = [
self.os_release_attr("version_id"),
self.lsb_release_attr("release"),
self.distro_release_attr("version_id"),
self._parse_distro_release_content(self.os_release_attr("pretty_name")).get(
"version_id", ""
self.os_release_attr('version_id'),
self.lsb_release_attr('release'),
self.distro_release_attr('version_id'),
self._parse_distro_release_content(self.os_release_attr('pretty_name')).get(
'version_id', '',
),
self._parse_distro_release_content(
self.lsb_release_attr("description")
).get("version_id", ""),
self.uname_attr("release"),
self.lsb_release_attr('description'),
).get('version_id', ''),
self.uname_attr('release'),
]
version = ""
version = ''
if best:
# This algorithm uses the last version in priority order that has
# the best precision. If the versions are not in conflict, that
# does not matter; otherwise, using the last one instead of the
# first one might be considered a surprise.
for v in versions:
if v.count(".") > version.count(".") or version == "":
if v.count('.') > version.count('.') or version == '':
version = v
else:
for v in versions:
if v != "":
if v != '':
version = v
break
if pretty and version and self.codename():
version = "{0} ({1})".format(version, self.codename())
version = f'{version} ({self.codename()})'
return version
def version_parts(self, best=False):
@ -888,12 +886,12 @@ class LinuxDistribution(object):
"""
version_str = self.version(best=best)
if version_str:
version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?")
version_regex = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?')
matches = version_regex.match(version_str)
if matches:
major, minor, build_number = matches.groups()
return major, minor or "", build_number or ""
return "", "", ""
return major, minor or '', build_number or ''
return '', '', ''
def major_version(self, best=False):
# type: (bool) -> str
@ -929,7 +927,7 @@ class LinuxDistribution(object):
For details, see :func:`distro.like`.
"""
return self.os_release_attr("id_like") or ""
return self.os_release_attr('id_like') or ''
def codename(self):
# type: () -> str
@ -941,12 +939,12 @@ class LinuxDistribution(object):
try:
# Handle os_release specially since distros might purposefully set
# this to empty string to have no codename
return self._os_release_info["codename"]
return self._os_release_info['codename']
except KeyError:
return (
self.lsb_release_attr("codename")
or self.distro_release_attr("codename")
or ""
self.lsb_release_attr('codename') or
self.distro_release_attr('codename') or
''
)
def info(self, pretty=False, best=False):
@ -1019,7 +1017,7 @@ class LinuxDistribution(object):
For details, see :func:`distro.os_release_attr`.
"""
return self._os_release_info.get(attribute, "")
return self._os_release_info.get(attribute, '')
def lsb_release_attr(self, attribute):
# type: (str) -> str
@ -1029,7 +1027,7 @@ class LinuxDistribution(object):
For details, see :func:`distro.lsb_release_attr`.
"""
return self._lsb_release_info.get(attribute, "")
return self._lsb_release_info.get(attribute, '')
def distro_release_attr(self, attribute):
# type: (str) -> str
@ -1039,7 +1037,7 @@ class LinuxDistribution(object):
For details, see :func:`distro.distro_release_attr`.
"""
return self._distro_release_info.get(attribute, "")
return self._distro_release_info.get(attribute, '')
def uname_attr(self, attribute):
# type: (str) -> str
@ -1049,7 +1047,7 @@ class LinuxDistribution(object):
For details, see :func:`distro.uname_attr`.
"""
return self._uname_info.get(attribute, "")
return self._uname_info.get(attribute, '')
@cached_property
def _os_release_info(self):
@ -1092,7 +1090,7 @@ class LinuxDistribution(object):
# parsed content is a unicode object. The following fix resolves that
# (... but it should be fixed in shlex...):
if sys.version_info[0] == 2 and isinstance(lexer.wordchars, bytes):
lexer.wordchars = lexer.wordchars.decode("iso-8859-1")
lexer.wordchars = lexer.wordchars.decode('iso-8859-1')
tokens = list(lexer)
for token in tokens:
@ -1102,32 +1100,32 @@ class LinuxDistribution(object):
# stripped, etc.), so the tokens are now either:
# * variable assignments: var=value
# * commands or their arguments (not allowed in os-release)
if "=" in token:
k, v = token.split("=", 1)
if '=' in token:
k, v = token.split('=', 1)
props[k.lower()] = v
else:
# Ignore any tokens that are not variable assignments
pass
if "version_codename" in props:
if 'version_codename' in props:
# os-release added a version_codename field. Use that in
# preference to anything else Note that some distros purposefully
# do not have code names. They should be setting
# version_codename=""
props["codename"] = props["version_codename"]
elif "ubuntu_codename" in props:
props['codename'] = props['version_codename']
elif 'ubuntu_codename' in props:
# Same as above but a non-standard field name used on older Ubuntus
props["codename"] = props["ubuntu_codename"]
elif "version" in props:
props['codename'] = props['ubuntu_codename']
elif 'version' in props:
# If there is no version_codename, parse it from the version
match = re.search(r"(\(\D+\))|,(\s+)?\D+", props["version"])
match = re.search(r'(\(\D+\))|,(\s+)?\D+', props['version'])
if match:
codename = match.group()
codename = codename.strip("()")
codename = codename.strip(",")
codename = codename.strip('()')
codename = codename.strip(',')
codename = codename.strip()
# codename appears within paranthese.
props["codename"] = codename
props['codename'] = codename
return props
@ -1142,9 +1140,9 @@ class LinuxDistribution(object):
"""
if not self.include_lsb:
return {}
with open(os.devnull, "wb") as devnull:
with open(os.devnull, 'wb') as devnull:
try:
cmd = ("lsb_release", "-a")
cmd = ('lsb_release', '-a')
stdout = subprocess.check_output(cmd, stderr=devnull)
# Command not found or lsb_release returned error
except (OSError, subprocess.CalledProcessError):
@ -1169,20 +1167,20 @@ class LinuxDistribution(object):
"""
props = {}
for line in lines:
kv = line.strip("\n").split(":", 1)
kv = line.strip('\n').split(':', 1)
if len(kv) != 2:
# Ignore lines without colon.
continue
k, v = kv
props.update({k.replace(" ", "_").lower(): v.strip()})
props.update({k.replace(' ', '_').lower(): v.strip()})
return props
@cached_property
def _uname_info(self):
# type: () -> Dict[str, str]
with open(os.devnull, "wb") as devnull:
with open(os.devnull, 'wb') as devnull:
try:
cmd = ("uname", "-rs")
cmd = ('uname', '-rs')
stdout = subprocess.check_output(cmd, stderr=devnull)
except OSError:
return {}
@ -1193,25 +1191,25 @@ class LinuxDistribution(object):
def _parse_uname_content(lines):
# type: (Sequence[str]) -> Dict[str, str]
props = {}
match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip())
match = re.search(r'^([^\s]+)\s+([\d\.]+)', lines[0].strip())
if match:
name, version = match.groups()
# This is to prevent the Linux kernel version from
# appearing as the 'best' version on otherwise
# identifiable distributions.
if name == "Linux":
if name == 'Linux':
return {}
props["id"] = name.lower()
props["name"] = name
props["release"] = version
props['id'] = name.lower()
props['name'] = name
props['release'] = version
return props
@staticmethod
def _to_str(text):
# type: (Union[bytes, str]) -> str
encoding = sys.getfilesystemencoding()
encoding = "utf-8" if encoding == "ascii" else encoding
encoding = 'utf-8' if encoding == 'ascii' else encoding
if sys.version_info[0] >= 3:
if isinstance(text, bytes):
@ -1241,10 +1239,10 @@ class LinuxDistribution(object):
# file), because we want to use what was specified as best as
# possible.
match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
if "name" in distro_info and "cloudlinux" in distro_info["name"].lower():
distro_info["id"] = "cloudlinux"
if 'name' in distro_info and 'cloudlinux' in distro_info['name'].lower():
distro_info['id'] = 'cloudlinux'
elif match:
distro_info["id"] = match.group(1)
distro_info['id'] = match.group(1)
return distro_info
else:
try:
@ -1259,21 +1257,21 @@ class LinuxDistribution(object):
# /etc for information. If they turn out to not be there the
# error is handled in `_parse_distro_release_file()`.
basenames = [
"SuSE-release",
"arch-release",
"base-release",
"centos-release",
"fedora-release",
"gentoo-release",
"mageia-release",
"mandrake-release",
"mandriva-release",
"mandrivalinux-release",
"manjaro-release",
"oracle-release",
"redhat-release",
"sl-release",
"slackware-version",
'SuSE-release',
'arch-release',
'base-release',
'centos-release',
'fedora-release',
'gentoo-release',
'mageia-release',
'mandrake-release',
'mandriva-release',
'mandrivalinux-release',
'manjaro-release',
'oracle-release',
'redhat-release',
'sl-release',
'slackware-version',
]
for basename in basenames:
if basename in _DISTRO_RELEASE_IGNORE_BASENAMES:
@ -1282,12 +1280,12 @@ class LinuxDistribution(object):
if match:
filepath = os.path.join(self.etc_dir, basename)
distro_info = self._parse_distro_release_file(filepath)
if "name" in distro_info:
if 'name' in distro_info:
# The name is always present if the pattern matches
self.distro_release_file = filepath
distro_info["id"] = match.group(1)
if "cloudlinux" in distro_info["name"].lower():
distro_info["id"] = "cloudlinux"
distro_info['id'] = match.group(1)
if 'cloudlinux' in distro_info['name'].lower():
distro_info['id'] = 'cloudlinux'
return distro_info
return {}
@ -1308,7 +1306,7 @@ class LinuxDistribution(object):
# Only parse the first line. For instance, on SLES there
# are multiple lines. We don't want them...
return self._parse_distro_release_content(fp.readline())
except (OSError, IOError):
except OSError:
# Ignore not being able to read a specific, seemingly version
# related file.
# See https://github.com/python-distro/distro/issues/162
@ -1331,13 +1329,13 @@ class LinuxDistribution(object):
distro_info = {}
if matches:
# regexp ensures non-None
distro_info["name"] = matches.group(3)[::-1]
distro_info['name'] = matches.group(3)[::-1]
if matches.group(2):
distro_info["version_id"] = matches.group(2)[::-1]
distro_info['version_id'] = matches.group(2)[::-1]
if matches.group(1):
distro_info["codename"] = matches.group(1)[::-1]
distro_info['codename'] = matches.group(1)[::-1]
elif line:
distro_info["name"] = line.strip()
distro_info['name'] = line.strip()
return distro_info
@ -1350,24 +1348,24 @@ def main():
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
parser = argparse.ArgumentParser(description="OS distro info tool")
parser = argparse.ArgumentParser(description='OS distro info tool')
parser.add_argument(
"--json", "-j", help="Output in machine readable format", action="store_true"
'--json', '-j', help='Output in machine readable format', action='store_true',
)
parser.add_argument(
"--root-dir",
"-r",
'--root-dir',
'-r',
type=str,
dest="root_dir",
help="Path to the root filesystem directory (defaults to /)",
dest='root_dir',
help='Path to the root filesystem directory (defaults to /)',
)
args = parser.parse_args()
if args.root_dir:
dist = LinuxDistribution(
include_lsb=False, include_uname=False, root_dir=args.root_dir
include_lsb=False, include_uname=False, root_dir=args.root_dir,
)
else:
dist = _distro
@ -1375,12 +1373,12 @@ def main():
if args.json:
logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))
else:
logger.info("Name: %s", dist.name(pretty=True))
logger.info('Name: %s', dist.name(pretty=True))
distribution_version = dist.version(pretty=True)
logger.info("Version: %s", distribution_version)
logger.info('Version: %s', distribution_version)
distribution_codename = dist.codename()
logger.info("Codename: %s", distribution_codename)
logger.info('Codename: %s', distribution_codename)
if __name__ == "__main__":
if __name__ == '__main__':
main()