Beispiel #1
0
    def __init__(self):
        self.os_version = None
        self.os_version_name = None
        self.is_linux = platform.system() == "Linux"
        self.linux_distro = None
        self.is_windows = platform.system() == "Windows"
        self.is_macos = platform.system() == "Darwin"
        self.is_freebsd = platform.system() == "FreeBSD"
        self.is_solaris = platform.system() == "SunOS"

        if self.is_linux:
            import distro
            self.linux_distro = distro.id()
            self.os_version = Version(distro.version())
            version_name = distro.codename()
            self.os_version_name = version_name if version_name != "n/a" else ""
            if not self.os_version_name and self.linux_distro == "debian":
                self.os_version_name = self.get_debian_version_name(self.os_version)
        elif self.is_windows:
            self.os_version = self.get_win_os_version()
            self.os_version_name = self.get_win_version_name(self.os_version)
        elif self.is_macos:
            self.os_version = Version(platform.mac_ver()[0])
            self.os_version_name = self.get_osx_version_name(self.os_version)
        elif self.is_freebsd:
            self.os_version = self.get_freebsd_version()
            self.os_version_name = "FreeBSD %s" % self.os_version
        elif self.is_solaris:
            self.os_version = Version(platform.release())
            self.os_version_name = self.get_solaris_version_name(self.os_version)
Beispiel #2
0
    def __init__(self) -> None:
        """
        Creates a new HostDistribution instance.
        """

        try:
            import distro
            self._id = distro.id()
            self._name = distro.name(pretty=False)
            self._fullname = distro.name(pretty=True)

            try:
                self._major = int(distro.major_version())
            except ValueError:
                self._major = -1

            try:
                self._minor = int(distro.minor_version())
            except ValueError:
                self._minor = -1

            try:
                self._build = int(distro.build_number())
            except ValueError:
                self._build = -1

            self._versionstring = distro.version(pretty=False)
            self._codename = distro.codename()
            self._like = distro.like()
        except ImportError:
            from suisei.murasame.exceptions import MissingRequirementError
            raise MissingRequirementError(
                'HostDistribution requires the distro package.',
                requirement='distro')
Beispiel #3
0
def check_distribution():
    '''
    Check if the distribution is supported by the installer.

    :return: The codename of the distribution
    '''
    bionic_code_names = ['bionic', 'tara', 'tessa', 'tina', 'disco']
    debian_code_names = ['buster', 'stretch', 'kali-rolling']
    focal_code_names = ['focal', 'ulyana', 'ulyssa', 'uma']

    codename = distro.codename().lower()
    if codename in bionic_code_names:
        logging.debug('Ubuntu 18.04 detected')
        return 'bionic'
    if codename in focal_code_names:
        logging.debug('Ubuntu 20.04 detected')
        return 'focal'
    if codename in debian_code_names:
        logging.debug('Debian/Kali detected')
        return 'debian'
    if distro.id() == 'fedora':
        logging.debug('Fedora detected')
        return 'fedora'
    logging.critical(
        'Your Distribution ({} {}) is not supported. FACT Installer requires Ubuntu 18.04, 20.04 or compatible!'
        .format(distro.id(), distro.version()))
    sys.exit(1)
def test_analyze_playability_invalid_wma():
    # Liquisoap does not fail with wma files on buster, bullseye, focal, jammy
    if distro.codename() in ("buster", "bullseye", "focal", "jammy"):
        return

    with pytest.raises(UnplayableFileError):
        test_analyze_playability(FILE_INVALID_DRM)
Beispiel #5
0
def _get_distro_info() -> Tuple[str, str, str, str]:
    if psutil.WINDOWS:
        return "windows", platform.system(), platform.release(), ""
    elif psutil.OSX:
        import plistlib

        with open("/System/Library/CoreServices/SystemVersion.plist",
                  "rb") as f:
            sw_vers = plistlib.load(f)
        return "mac", sw_vers["ProductName"], sw_vers["ProductVersion"], ""
    elif _is_android():
        import subprocess

        android_version = subprocess.run(
            ["getprop", "ro.build.version.release"],
            check=True,
            stdout=subprocess.PIPE,
        ).stdout
        return "android", "Android", android_version.decode().strip(), ""
    elif psutil.LINUX:
        import distro

        return distro.id(), distro.name(), distro.version(), distro.codename()

    raise NotImplementedError("unsupported OS")
Beispiel #6
0
    def __init__(self):
        self.os_version = None
        self.os_version_name = None
        self.is_linux = platform.system() == "Linux"
        self.linux_distro = None
        self.is_windows = platform.system() == "Windows"
        self.is_macos = platform.system() == "Darwin"
        self.is_freebsd = platform.system() == "FreeBSD"
        self.is_solaris = platform.system() == "SunOS"

        if self.is_linux:
            import distro
            self.linux_distro = distro.id()
            self.os_version = Version(distro.version())
            version_name = distro.codename()
            self.os_version_name = version_name if version_name != "n/a" else ""
            if not self.os_version_name and self.linux_distro == "debian":
                self.os_version_name = self.get_debian_version_name(
                    self.os_version)
        elif self.is_windows:
            self.os_version = self.get_win_os_version()
            self.os_version_name = self.get_win_version_name(self.os_version)
        elif self.is_macos:
            self.os_version = Version(platform.mac_ver()[0])
            self.os_version_name = self.get_osx_version_name(self.os_version)
        elif self.is_freebsd:
            self.os_version = self.get_freebsd_version()
            self.os_version_name = "FreeBSD %s" % self.os_version
        elif self.is_solaris:
            self.os_version = Version(platform.release())
            self.os_version_name = self.get_solaris_version_name(
                self.os_version)
Beispiel #7
0
 def _get_linux_distro_info(self):
     import distro
     self.linux_distro = distro.id()
     self.os_version = Version(distro.version())
     version_name = distro.codename()
     self.os_version_name = version_name if version_name != "n/a" else ""
     if not self.os_version_name and self.linux_distro == "debian":
         self.os_version_name = self.get_debian_version_name(self.os_version)
Beispiel #8
0
def get_distribution_version():
    """
    Function to acquire current Distribution Version

    This function will return the current distribution version
    if the user is running on a Linux machine.
    """
    return distro.codename()
Beispiel #9
0
def test_compute_replaygain(filepath, replaygain):
    tolerance = 0.8

    # On bionic, replaygain is a bit higher for loud mp3 files.
    # This huge tolerance makes the test pass, with values devianting from ~-17 to ~-13
    if distro.codename() == "bionic" and str(filepath).endswith("+12.mp3"):
        tolerance = 5

    assert compute_replaygain(filepath) == pytest.approx(replaygain,
                                                         abs=tolerance)
def test_analyze_replaygain(filepath, replaygain):
    tolerance = 0.8

    # On bionic, replaygain is a bit higher for loud mp3 files.
    # This huge tolerance makes the test pass, with values devianting from ~-17 to ~-13
    if distro.codename() == "bionic" and str(filepath).endswith("+12.mp3"):
        tolerance = 5

    metadata = analyze_replaygain(filepath, dict())
    assert metadata["replay_gain"] == pytest.approx(replaygain, abs=tolerance)
Beispiel #11
0
def get_os_distribution():
    try:
        return platform.dist()
    except Exception:
        import distro
        return [
            distro.name(),
            distro.major_version() + '.' + distro.minor_version(),
            distro.codename()
        ]
Beispiel #12
0
 def __init__(self, lsb_name, get_version_fn=None):
     self.lsb_name = lsb_name
     if distro.__name__ == "distro":
         self.lsb_info = (distro.id(), distro.version(), distro.codename())
     elif hasattr(distro, "linux_distribution"):
         self.lsb_info = distro.linux_distribution(full_distribution_name=0)
     elif hasattr(distro, "dist"):
         self.lsb_info = distro.dist()
     else:
         self.lsb_info = None
Beispiel #13
0
def check_distribution():
    codename = distro.codename().lower()
    if codename in XENIAL_CODE_NAMES:
        logging.debug('Ubuntu 16.04 detected')
        return 'xenial'
    if codename in BIONIC_CODE_NAMES:
        logging.debug('Ubuntu 18.04 detected')
        return 'bionic'
    else:
        sys.exit('Your Distribution ({} {}) is not supported. FACT Installer requires Ubuntu 16.04, Ubuntu 18.04 or compatible!'.format(distro.id(), distro.version()))
Beispiel #14
0
 def __init__(self, batch=False):
     self.batch = batch
     # self.asroot = ifroot()
     self._services = set()
     self._system_packages = set()
     if ifroot():
         click.echo("Running as root.")
     click.echo("This is getlino version {} running on {} ({} {}).".format(
         SETUP_INFO['version'], distro.name(pretty=True), distro.id(),
         distro.codename()))
Beispiel #15
0
def check_for_supported_os(config, provider):
    """
    Checks if VNet is running on a supported OS for a provider
    :param dict config: The config generated by get_config()
    :param str provider: The provider to check OS support for
    :return: bool: True if the current OS is supported, False otherwise
    """
    logger.debug(
        "Checking if your os is supported for provider {}".format(provider))
    return codename().lower(
    ) in config["providers"][provider]["supported_operating_systems"]
    def _collect_os_default(self):
        os_info = dict()
        os_info["system"] = platform.system()
        os_info["release"] = platform.release()
        os_info["like"] = distro.like()
        os_info["build_number"] = distro.build_number()
        os_info["version"] = distro.version()
        os_info["name"] = distro.name()
        os_info["codename"] = distro.codename()

        self._logger.debug(os_info)
        return os_info
def get_codename_to_test():
    try:
        import distro
        if distro.id() == 'ubuntu-core':
            codename = 'focal'
            if distro.version() == '18':
                codename = 'bionic'
            elif distro.version() == '16':
                codename = 'xenial'
            return codename
        return distro.codename().split()[0].lower()
    except (ImportError, CalledProcessError):
        import lsb_release
        lsb_release.get_distro_information()["CODENAME"]
Beispiel #18
0
def check_distribution():
    try:
        import distro
    except ImportError:
        errors = subprocess.run('sudo -EH pip3 install distro', shell=True).stderr
        if errors:
            sys.exit('Could not determine the system´s Linux distribution')
        else:
            import distro
    codename = distro.codename().lower()
    supported_ubuntu_xenial_code_names = ['xenial xerus', 'yakkety yak', 'sarah', 'serena', 'sonya', 'sylvia']
    if codename in supported_ubuntu_xenial_code_names:
        logging.debug('Ubuntu 16.04 detected')
        return 'xenial'
    else:
        sys.exit('Your Distribution ({} {}) is not supported. FACT Installer requires Ubuntu 16.04 or compatible!'.format(distro.id(), distro.version()))
Beispiel #19
0
def check_distribution():
    codename = distro.codename().lower()
    if codename in BIONIC_CODE_NAMES:
        logging.debug('Ubuntu 18.04 detected')
        return 'bionic'
    if codename in FOCAL_CODE_NAMES:
        logging.debug('Ubuntu 20.04 detected')
        return 'focal'
    if codename in DEBIAN_CODE_NAMES:
        logging.debug('Debian/Kali detected')
        return 'debian'
    if distro.id() == 'fedora':
        logging.debug('Fedora detected')
        return 'fedora'
    sys.exit(
        'Your Distribution ({} {}) is not supported. FACT Installer requires Ubuntu 18.04, 20.04 or compatible!'
        .format(distro.id(), distro.version()))
Beispiel #20
0
def check_distribution():
    codename = distro.codename().lower()
    if codename in XENIAL_CODE_NAMES:
        logging.debug('Ubuntu 16.04 detected')
        return 'xenial'
    if codename in BIONIC_CODE_NAMES:
        logging.debug('Ubuntu 18.04 detected')
        return 'bionic'
    if codename in FOCAL_CODE_NAMES:
        logging.debug('Ubuntu 20.04 detected')
        return 'focal'
    if codename in BUSTER_CODE_NAMES:
        logging.debug('Debian 10/Kali detected')
        return 'buster'
    if codename in BULLSEYE_CODE_NAMES:
        logging.debug('Debian 11 detected')
        return 'bullseye'
    sys.exit('Your Distribution ({} {}) is not supported. FACT Extractor Installer requires Ubuntu 16.04, 18.04, 20.04, or compatible!'.format(distro.id(), distro.version()))
Beispiel #21
0
def main():
    args = Options()
    ColorScheme(args.color)
    sections = args.section
    if (len(sections) == 0):
        sections = [
            'header', 'hw', 'load', 'net', 'netsrv', 'security', 'agents'
        ]
    print(
        TITLE +
        "======================================================================"
        + DEFAULT)
    print('{:^70}'.format(version))
    print(
        TITLE +
        "======================================================================"
        + DEFAULT)
    for i in range(len(sections)):
        # HEADER
        if (sections[i] == 'header'):
            hostname = gethostname()
            row('NAME', hostname)
            now = time.strftime("%Y-%m-%d %H:%M (%Z)")
            row('DATE', now)
            loadavg = os.getloadavg()
            uptime = countuptime() + " " + str(os.getloadavg())
            row('UPTIME', uptime)
            if using_distro:
                platf = distro.name() + " " + distro.version(
                ) + " " + distro.codename()
            else:
                platf = ' '.join(platform.linux_distribution())
            row('OS', platf)
            kernelv = platform.platform()
            row('KERNEL', kernelv)
# HARDWARE
        if (sections[i] == 'hw'):
            title('HARDWARE')
            dmidecode()
            checkvz()
            cpuinfo()
            meminfo()
            disk()
            netcards()
Beispiel #22
0
def test_compute_silences(filepath, length, cuein, cueout):
    result = compute_silences(filepath)

    if cuein != 0.0:
        assert len(result) > 0
        first = result.pop(0)
        assert first[0] == pytest.approx(0.0, abs=0.1)
        assert first[1] == pytest.approx(cuein, abs=1)

    if cueout != length:
        # ffmpeg v3 (bionic) does not warn about silence end when the track ends.
        # Check for infinity on last silence ending
        if distro.codename() == "bionic":
            length = inf

        assert len(result) > 0
        last = result.pop()
        assert last[0] == pytest.approx(cueout, abs=1)
        assert last[1] == pytest.approx(length, abs=0.1)
Beispiel #23
0
def _get_distro_info():
    if psutil.WINDOWS:
        return "windows", platform.system(), platform.release(), ""
    elif psutil.OSX:
        from plistlib import readPlist

        sw_vers = readPlist("/System/Library/CoreServices/SystemVersion.plist")
        return "mac", sw_vers["ProductName"], sw_vers["ProductVersion"], ""
    elif _is_android():
        from subprocess import check_output

        android_version = check_output(["getprop", "ro.build.version.release"])
        return "android", "Android", android_version.decode().strip(), ""
    elif psutil.LINUX:
        import distro

        return distro.id(), distro.name(), distro.version(), distro.codename()

    raise NotImplementedError("unsupported OS")
Beispiel #24
0
    def detect(cls):
        system = platform.system().lower()
        if system == 'windows':
            dist = 'windows'
            version, *_ = platform.win32_ver()
            codename = None
        elif system == 'darwin':
            dist = 'macos'
            version, *_ = platform.mac_ver()
            codename = None
        else:
            dist = distro.id()
            version = distro.version()
            codename = distro.codename()

        return cls(arch=platform.machine(),
                   system=system,
                   distro=dist,
                   version=version,
                   codename=codename)
Beispiel #25
0
def check_distribution():
    try:
        import distro
    except ImportError:
        errors = subprocess.run('sudo -EH pip3 install distro',
                                shell=True).stderr
        if errors:
            sys.exit('Could not determine the system´s Linux distribution')
        else:
            import distro
    codename = distro.codename().lower()
    if codename in XENIAL_CODE_NAMES:
        logging.debug('Ubuntu 16.04 detected')
        return 'xenial'
    if codename in BIONIC_CODE_NAMES:
        logging.debug('Ubuntu 18.04 detected')
        return 'bionic'
    else:
        sys.exit(
            'Your Distribution ({} {}) is not supported. FACT Installer requires Ubuntu 16.04, Ubuntu 18.04 or compatible!'
            .format(distro.id(), distro.version()))
Beispiel #26
0
    def check_available_fix(self):
        if self.distro_info != "local":
            distro_name, distro_codename = self.distro_info.split("-")
        else:
            distro_name = distro.id()
            distro_codename = distro.codename()

        if distro_name in DEBIAN_DISTROS:
            debian_tracker = DebianCVETracker(distro_name, distro_codename,
                                              self.is_backport)
            debian_tracker.cve_info(self.all_cve_data)
        elif distro_name in REDHAT_DISTROS:
            redhat_tracker = RedhatCVETracker(distro_name, distro_codename)
            redhat_tracker.cve_info(self.all_cve_data)
        elif self.is_backport:
            LOGGER.info(
                f"CVE Binary Tool doesn't support Backported Fix Utility for {distro_name.capitalize()} at the moment."
            )
        else:
            LOGGER.info(
                f"CVE Binary Tool doesn't support Available Fix Utility for {distro_name.capitalize()} at the moment."
            )
Beispiel #27
0
import distro
import platform

# Параметры системы
OS_RELEASE = distro.codename().split(' ')[0].lower()
PLATFORM_ARCH = platform.machine()
OS_DISTRIBUTION = distro.id().lower()
OS_VERSION = distro.major_version()

# Адрес загрузки исходного кода nginx
NGINX_URL = "http://nginx.org/download"
NGINX_SRPM_URL_MAINLINE = "http://nginx.org/packages/mainline/centos/{}/SRPMS".format(
    OS_VERSION)
NGINX_SRPM_URL_STABLE = "http://nginx.org/packages/centos/{}/SRPMS".format(
    OS_VERSION)

# Архив со скриптами для создания пакета
DEB_PACKAGE_SCRIPTS_URL_MAINLINE = "http://nginx.org/packages/mainline/{}/pool/nginx/n/nginx".format(
    OS_DISTRIBUTION)
DEB_PACKAGE_SCRIPTS_URL_STABLE = "http://nginx.org/packages/{}/pool/nginx/n/nginx".format(
    OS_DISTRIBUTION)

# Путь до директории сборки пакета
SRC_PATH = "/usr/src/nginx"

# Error build code
DPKG_FAIL_EXIT_CODE = 29

# Параметры компиляции nginx
DEFAULT_CONFIGURE_PARAMS = [
    "--prefix=/etc/nginx",
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# 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.

import distro

print 'os_release_info: {0}'.format(distro.os_release_info())
print 'lsb_release_info: {0}'.format(distro.lsb_release_info())
print 'distro_release_info: {0}'.format(distro.distro_release_info())
print 'id: {0}'.format(distro.id())
print 'name: {0}'.format(distro.name())
print 'name_pretty: {0}'.format(distro.name(True))
print 'version: {0}'.format(distro.version())
print 'version_pretty: {0}'.format(distro.version(True))
print 'like: {0}'.format(distro.like())
print 'codename: {0}'.format(distro.codename())
print 'linux_distribution_full: {0}'.format(distro.linux_distribution())
print 'linux_distribution: {0}'.format(distro.linux_distribution(False))
print 'major_version: {0}'.format(distro.major_version())
print 'minor_version: {0}'.format(distro.minor_version())
print 'build_number: {0}'.format(distro.build_number())
Beispiel #29
0
    def platform_profiles(self):
        if platform.system() == 'Darwin':
            atoms = set(['darwin'])
            # detect available macos package managers
            if os.system('which brew >/dev/null') == 0:
                atoms.add('brew')
                self.platform = Brew()
            return ["platform:%s" % (atom,) for atom in sorted(atoms)]
        distro_id = distro.id()
        if not distro_id:
            log = logging.getLogger(__name__)
            log.error('Unable to determine distro ID. '
                      'Does /etc/os-release exist or '
                      'is lsb_release installed?')
            raise Exception('Distro name not found')
        # NOTE(toabctl): distro can be more than one string (i.e. "SUSE LINUX")
        codename = distro.codename().lower()
        release = distro.version().lower()
        # NOTE(toabctl): space is a delimiter for bindep, so remove the spaces
        distro_id = "".join(distro_id.split()).lower()
        atoms = set([distro_id])
        atoms.update(self.codenamebits(distro_id, codename))
        atoms.update(self.releasebits(distro_id, release))
        if distro_id in ["debian", "ubuntu"]:
            atoms.add("dpkg")
            self.platform = Dpkg()
        # RPM distros seem to be especially complicated
        elif distro_id in ["amzn", "amazonami",
                           "centos", "rhel",
                           "redhatenterpriseserver",
                           "redhatenterpriseworkstation",
                           "fedora",
                           "opensuseproject", "opensuse", "opensuse-leap",
                           "opensuse-tumbleweed", "sles", "suselinux"]:
            # Distro aliases
            if distro_id in ["redhatenterpriseserver",
                             "redhatenterpriseworkstation"]:
                # just short alias
                atoms.add("rhel")
                atoms.update(self.codenamebits("rhel", codename))
                atoms.update(self.releasebits("rhel", release))
            elif distro_id == 'rhel' and 'server' in distro.name().lower():
                atoms.add("redhatenterpriseserver")
                atoms.update(self.codenamebits("redhatenterpriseserver",
                                               codename))
                atoms.update(self.releasebits("redhatenterpriseserver",
                                              release))
            elif (distro_id == 'rhel' and
                    'workstation' in distro.name().lower()):
                atoms.add("redhatenterpriseworkstation")
                atoms.update(self.codenamebits("redhatenterpriseworkstation",
                                               codename))
                atoms.update(self.releasebits("redhatenterpriseworkstation",
                                              release))
            elif "amzn" in distro_id:
                atoms.add("amazonami")
                atoms.update(self.codenamebits("amazonami", codename))
                atoms.update(self.releasebits("amazonami", release))
            elif "amazonami" in distro_id:
                atoms.add("amzn")
                atoms.update(self.codenamebits("amzn", codename))
                atoms.update(self.releasebits("amzn", release))
            elif "opensuse" in distro_id:
                # just short alias
                atoms.add("opensuse")
                atoms.update(self.codenamebits("opensuse", codename))
                atoms.update(self.releasebits("opensuse", release))
                atoms.add("opensuseproject")
                atoms.update(self.codenamebits("opensuseproject", codename))
                atoms.update(self.releasebits("opensuseproject", release))
            elif "sles" in distro_id:
                atoms.add("suselinux")
                atoms.update(self.codenamebits("suselinux", codename))
                atoms.update(self.releasebits("suselinux", release))
            elif "suselinux" in distro_id:
                atoms.add("sles")
                atoms.update(self.codenamebits("sles", codename))
                atoms.update(self.releasebits("sles", release))

            # Family aliases
            if 'suse' in distro_id or distro_id == 'sles':
                atoms.add("suse")
            else:
                atoms.add("redhat")

            atoms.add("rpm")
            self.platform = Rpm()
        elif distro_id in ["gentoo"]:
            atoms.add("emerge")
            self.platform = Emerge()
        elif distro_id in ["arch"]:
            atoms.add("pacman")
            self.platform = Pacman()
        elif distro_id in ["alpine"]:
            atoms.add("apk")
            self.platform = Apk()
        else:
            self.platform = Unknown()
        return ["platform:%s" % (atom,) for atom in sorted(atoms)]
Beispiel #30
0
 def linux_distribution():
     return (name(), version(), codename())
Beispiel #31
0
class Requirement():
    """
    Requirement parser
    """
    _parser = None
    _lookup: Dict[str, str] = dict(
        distro_codename=distro.codename(),
        distro_id=distro.id(),
        distro_like=distro.like(),
        distro_name=distro.name(),
        distro_version=distro.version(),
        os_name=os.name,
        platform_machine=platform.machine(),
        platform_python_implementation=platform.python_implementation(),
        platform_release=platform.release(),
        platform_system=platform.system(),
        platform_version=platform.version(),
        platform_full_version=platform.python_version(),
        python_version=platform.python_version()[:3],
        sys_platform=sys.platform)

    def __init__(self, s):
        self._parser = parsley.makeGrammar(
            GRAMMAR, {"lookup": self._lookup.__getitem__})
        self._parsed_requirement = self._parser(s).specification()

    @property
    def name(self):
        """
        Get the name part of the requirement
        """
        return self._parsed_requirement[0]

    @property
    def extra(self):
        """
        Get the extras from the requirement
        """
        return self._parsed_requirement[1]

    @property
    def version_evals(self):
        """
        Return the version evaluations for the requirement if present
        """
        if not self._parsed_requirement[2]:
            return []
        return self._parsed_requirement[2]

    @property
    def env_evals(self):
        """
        Return any environment evaluations for the requirement
        """
        if not self._parsed_requirement[3]:
            return []
        return self._parsed_requirement[3]

    @property
    def env_matches(self):
        """
        Determine if the current env matches the requirement

        Returns
        -------
        True if it matches
        """
        env_evals = list(self.env_evals)
        env_evals = self.evaluate_matches(env_evals)
        if len(env_evals) == 3:
            env_evals = [self.evaluate(*env_evals)]
        return False not in env_evals

    def evaluate_matches(self, env_evals):
        """
        Evaluate all of the statements and return a list of the results
        Parameters
        ----------
        env_evals: evals to be evaluated

        Returns
        -------
        Evaluates all the statements and return the ones that match
        """
        for element_num in range(len(env_evals)):  # pylint: disable=consider-using-enumerate
            entry = env_evals[element_num]
            if isinstance(entry, str):
                continue
            operation, val1, val2 = entry
            env_evals[element_num] = self.evaluate(operation, val1, val2)
        return env_evals

    def evaluate(self, operation, val1, val2):
        """Evaluate"""
        if isinstance(val1, tuple):
            val1 = self.evaluate(*val1)
        if isinstance(val2, tuple):
            val2 = self.evaluate(*val2)

        if isinstance(val1, str):
            val1 = pkg_resources.parse_version(val1)
        if isinstance(val2, str):
            val2 = pkg_resources.parse_version(val2)

        # statement = f'{val1} {operation} {val2}'

        result = None
        if operation == '>':
            result = val1 > val2
        elif operation == '<':
            result = val1 < val2
        elif operation == '>=':
            result = val1 >= val2
        elif operation == '<=':
            result = val1 <= val2
        elif operation == '==':
            result = val1 == val2
        elif operation in ['!', '!=']:
            result = val1 != val2
        elif operation == 'and':
            result = val1 and val2
        elif operation == 'or':
            result = val1 or val2
        else:
            logger.error(f'Invalid operation {operation}')
        # logger.debug(f'Evaluated {statement} == {result}')
        return result
Beispiel #32
0
class RepoError(Exception):
    """ Exception from this module."""
    def __init__(self, *args, code=1, **kwargs):
        """Exception with a source object

        Arguments:
            code (:obj:`int`, optional, default=1): Exception error code.
    """
        super().__init__(*args, **kwargs)
        self.code = code


try:
    import distro
    DISTRO_CODENAME = distro.codename()
except ImportError:
    DISTRO_CODENAME = 'linux'


class AptSourceType(Enum):
    """ Helper Enum to simplify saving data. """
    BINARY = "deb"
    SOURCE = "deb-src"


class AptSourceEnabled(Enum):
    """ Helper Enum to translate between bool data and the Deb822 format. """
    TRUE = 'yes'
    FALSE = 'no'
Beispiel #33
0
 def get_codename():
     codename = distro.codename()
     if not codename:
         codename = "UNKNOWN"
     return codename