Python pkg_resources.parse_version() Examples

The following are 30 code examples of pkg_resources.parse_version(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pkg_resources , or try the search function .
Example #1
Source File: version_comparator.py    From houndsploit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_equal_with_x(num_version, num_to_compare):
    """
    Check if the number of version searched by the user is equal to the number of version (with x) of the software
    contained in the vulnerability's description.
    :param num_version: the number of version searched by the user.
    :param num_to_compare: the number of version (containing the x) in the vulnerability's description.
    :return: True if the number of version searched by the user is equal to the number of version (with x) of the
                software contained in the vulnerability's description.
    """
    version_precision = str(num_to_compare).count('.')
    try:
        regex = re.search(r'\d+(\.\d+){0,%d}' % version_precision, num_version)
        num_version = regex.group()
    except AttributeError:
        pass
    if parse_version(num_version) == parse_version(num_to_compare):
        return True
    else:
        return False 
Example #2
Source File: env_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def fail_first_step_precondition_exception(self, scenario):
        """
        Fail first step in the given Scenario and add exception message for the output.
        This is needed because xUnit exporter in Behave fails if there are not failed steps.
        :param scenario: Behave's Scenario
        """

        try:
            import behave
            if parse_version(behave.__version__) < parse_version('1.2.6'):
                status = 'failed'
            else:
                status = behave.model_core.Status.failed
        except ImportError as exc:
            self.logger.error(exc)
            raise

        scenario.steps[0].status = status
        scenario.steps[0].exception = Exception("Preconditions failed")
        scenario.steps[0].error_message = str(self.error_exception) 
Example #3
Source File: api.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def __init__(self, url, key, client, version='0.10.8', headers={}, ssl_verify=True):
        self.url = url.rstrip('/')
        self.parsed_url = six.moves.urllib.parse.urlparse(self.url)
        if not isinstance(key, Key):
            key = Key(key)
        if not key.key:
            raise ValueError("ChefAPI attribute 'key' was invalid.")
        self.key = key
        self.client = client
        self.version = version
        self.headers = dict((k.lower(), v) for k, v in six.iteritems(headers))
        self.version_parsed = pkg_resources.parse_version(self.version)
        self.platform = self.parsed_url.hostname == 'api.opscode.com'
        self.ssl_verify = ssl_verify
        if not api_stack_value():
            self.set_default() 
Example #4
Source File: check.py    From slpkg with GNU General Public License v3.0 6 votes vote down vote up
def sbo_upgrade(skip, flag):
    """Return packages for upgrade
    """
    msg = Msg()
    black = BlackList()
    msg.checking()
    upgrade_names = []
    data = SBoGrep(name="").names()
    blacklist = list(black.get_black())
    for pkg in sbo_list():
        name = split_package(pkg)[0]
        ver = split_package(pkg)[1]
        if (name in data and name not in skip and name not in blacklist):
            sbo_package = f"{name}-{SBoGrep(name).version()}"
            package = f"{name}-{ver}"
            if parse_version(sbo_package) > parse_version(package):
                upgrade_names.append(name)
    msg.done()
    if "--checklist" in flag:
        upgrade_names = choose_upg(upgrade_names)
    return upgrade_names 
Example #5
Source File: installLttng.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def checkGCC():
    global System
    global gccMinVersion
    print "Checking GCC version..."
    command = "gcc --version | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'"
    out = runCommand(command)
    gccVersion = out.split("\n")[0]
    if parse_version(gccVersion) < parse_version(gccMinVersion):
        if "Ubuntu" in System or "ubuntu" in System:
            command = "sudo apt-get install gcc"
        elif "Amazon Linux AMI" in System:
            command = "sudo yum install gcc"
        runCommand2(command, "y\n")
    command = "gcc --version | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'"
    gccVersion = out.split("\n")[0]
    if parse_version(gccVersion) < parse_version(gccMinVersion):
        print "Error: GCC version is " + gccVersion + " < " + gccMinVersion
        sys.exit()
    else:
        print "GCC version is " + gccVersion + " >= " + gccMinVersion + bcolors.OKGREEN + " [OK]" + bcolors.ENDC 
Example #6
Source File: images.py    From armory with MIT License 6 votes vote down vote up
def is_old(tag: str):
    """
    Return True if tag is an old armory container, False otherwise

    If current version is dev, only returns True for old "-dev" containers.
    """
    if not isinstance(tag, str):
        raise ValueError(f"tag must be of type str, not type {type(tag)}")
    if tag in ALL:
        return False
    tokens = tag.split(":")
    if len(tokens) != 2:
        return False
    repo, tag = tokens
    if repo in REPOSITORIES:
        try:
            other = parse_version(tag)
            if other < VERSION:
                # return True if both prerelease or both not prerelease
                return not (other.is_prerelease ^ VERSION.is_prerelease)
        except (AttributeError, ValueError):
            # Catch empty tag and tag parsing errors
            pass
    return False 
Example #7
Source File: client.py    From jira with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _check_update_(self):
        """Check if the current version of the library is outdated."""
        try:
            data = requests.get(
                "https://pypi.python.org/pypi/jira/json", timeout=2.001
            ).json()

            released_version = data["info"]["version"]
            if parse_version(released_version) > parse_version(__version__):
                warnings.warn(
                    "You are running an outdated version of Jira Python %s. Current version is %s. Do not file any bugs against older versions."
                    % (__version__, released_version)
                )
        except requests.RequestException:
            pass
        except Exception as e:
            logging.warning(e) 
Example #8
Source File: __init__.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_assets(self):
        """Define the static assets the plugin offers."""
        octoprintVersion = pkg_resources.parse_version(octoprint.__version__)

        jsFiles = ["js/excluderegion.js"]

        # The modified gcode renderer is not needed for 1.3.10rc1 and above
        if (octoprintVersion < pkg_resources.parse_version("1.3.10rc1")):
            self._logger.info(
                "Octoprint {} is pre 1.3.10rc1, including renderer.js to override gcode viewer",
                octoprint.__display_version__
            )
            jsFiles.insert(0, "js/renderer.js")

        return dict(
            js=jsFiles,
            css=["css/excluderegion.css"]
        )

    # ~~ TemplatePlugin 
Example #9
Source File: pundle.py    From pundler with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_installed_version(self, suite, install=False):
        # install version of package if not installed
        dist = None
        if self.has_correct_freeze():
            dist = [
                installation
                for installation in self.installed
                if pkg_resources.parse_version(installation.version) == pkg_resources.parse_version(self.frozen)
            ]
            dist = dist[0] if dist else None
            if install and not dist:
                dist = self.install_frozen(suite)
        if install and not dist:
            dist = self.requirement.locate_and_install(suite, installed=self.get_installed())
            if dist is None:
                raise PundleException('Package %s was not installed due some error' % self.key)
            self.frozen = dist.version
            self.installed.append(dist)
            self.frozen = dist.version
        return dist 
Example #10
Source File: images.py    From armory with MIT License 6 votes vote down vote up
def parse_version(tag):
    """
    Return PEP 440 version for given version tag
    """
    if not isinstance(tag, str):
        raise ValueError(f"tag is a {type(tag)}, not a str")
    if tag.endswith(armory.DEV):
        numeric_tag = tag[: -len(armory.DEV)]
    else:
        numeric_tag = tag
    if len(numeric_tag.split(".")) != 3:
        raise ValueError(f"tag {tag} must be of form 'major.minor.patch[-dev]'")
    version = pkg_resources.parse_version(tag)
    if not isinstance(version, pkg_resources.extern.packaging.version.Version):
        raise ValueError(f"tag {tag} parses to type {type(version)}, not Version")
    return version 
Example #11
Source File: buildmeta.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def get_version() -> Version:
    if devmode.is_in_dev_mode():
        if pkg_resources is None:
            raise MetadataError(
                'cannot determine build version: no pkg_resources module')
        if setuptools_scm is None:
            raise MetadataError(
                'cannot determine build version: no setuptools_scm module')
        version = setuptools_scm.get_version(
            root='../..', relative_to=__file__)
        pv = pkg_resources.parse_version(version)
        version = parse_version(pv)
    else:
        vertuple: List[Any] = list(get_build_metadata_value('VERSION'))
        vertuple[2] = VersionStage(vertuple[2])
        version = Version(*vertuple)

    return version 
Example #12
Source File: earlyinit.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def check_qt_version():
    """Check if the Qt version is recent enough."""
    from PyQt5.QtCore import (qVersion, QT_VERSION, PYQT_VERSION,
                              PYQT_VERSION_STR)
    from pkg_resources import parse_version
    from qutebrowser.utils import log
    parsed_qversion = parse_version(qVersion())

    if (QT_VERSION < 0x050701 or PYQT_VERSION < 0x050700 or
            parsed_qversion < parse_version('5.7.1')):
        text = ("Fatal error: Qt >= 5.7.1 and PyQt >= 5.7 are required, "
                "but Qt {} / PyQt {} is installed.".format(qt_version(),
                                                           PYQT_VERSION_STR))
        _die(text)

    if qVersion().startswith('5.8.'):
        log.init.warning("Running qutebrowser with Qt 5.8 is untested and "
                         "unsupported!")

    if (parsed_qversion >= parse_version('5.12') and
            (PYQT_VERSION < 0x050c00 or QT_VERSION < 0x050c00)):
        log.init.warning("Combining PyQt {} with Qt {} is unsupported! Ensure "
                         "all versions are newer than 5.12 to avoid potential "
                         "issues.".format(PYQT_VERSION_STR, qt_version())) 
Example #13
Source File: setup.py    From pulse2percept with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_numpy_status():
    """
    Returns a dictionary containing a boolean specifying whether NumPy
    is up-to-date, along with the version string (empty string if
    not installed).
    """
    numpy_status = {}
    try:
        import numpy
        numpy_version = numpy.__version__
        numpy_status['up_to_date'] = parse_version(
            numpy_version) >= parse_version(NUMPY_MIN_VERSION)
        numpy_status['version'] = numpy_version
    except ImportError:
        traceback.print_exc()
        numpy_status['up_to_date'] = False
        numpy_status['version'] = ""
    return numpy_status 
Example #14
Source File: setup.py    From vidgear with Apache License 2.0 6 votes vote down vote up
def test_opencv():
    """
    This function is workaround to 
    test if correct OpenCV Library version has already been installed
    on the machine or not. Returns True if previously not installed.
    """
    try:
        # import OpenCV Binaries
        import cv2

        # check whether OpenCV Binaries are 3.x+
        if parse_version(cv2.__version__) < parse_version("3"):
            raise ImportError(
                "Incompatible (< 3.0) OpenCV version-{} Installation found on this machine!".format(
                    parse_version(cv2.__version__)
                )
            )
    except ImportError:
        return True
    return False 
Example #15
Source File: filter_query.py    From houndsploit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def filter_exploits_without_comparator(exploit, num_version, software_name, final_result_set):
    """
    Add the exploit (without comparator) to the final_result_set if respect the condition set by the user.
    :param exploit: the exploit we have to check if it has a number of version that matches the value passed by
                    the user.
    :param num_version: the number of version searched by the user.
    :param software_name: the name of the software searched by the user.
    :param final_result_set: the result set that
    :return: the result set that
    """
    if not exploit.description.__contains__('.x'):
        # exclude the exploit from results table if the number of version is not equal and contains 'x'
        try:
            if parse_version(num_version) == parse_version(get_num_version(software_name, exploit.description)):
                final_result_set.append(exploit)
        except TypeError:
            pass
    else:
        # exclude the exploit from results table if the number of version is not equal and not contains 'x'
        try:
            if is_equal_with_x(num_version, get_num_version(software_name, exploit.description)):
                final_result_set.append(exploit)
        except TypeError:
            pass
    return final_result_set 
Example #16
Source File: filter_query.py    From houndsploit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def filter_exploits_with_comparator_and_without_x(exploit, num_version, software_name, final_result_set):
    """
    Add exploit (with comparator and without the x in number version) to the final_result_set if respect the condition set by the user.
    :param exploit: the exploit we have to check if it has a number of version that matches the value passed by
                    the user.
    :param num_version: the number of version searched by the user.
    :param software_name: the name of the software searched by the user.
    :param final_result_set: the result set that
    :return: the result set that
    """
    if str_contains_num_version_range(str(exploit.description)):
        if is_in_version_range(num_version, software_name, exploit.description):
            final_result_set.append(exploit)
    else:
        try:
            if parse_version(num_version) <= parse_version(
                    get_num_version_with_comparator(software_name, exploit.description)):
                final_result_set.append(exploit)
        except TypeError:
            pass
    return final_result_set 
Example #17
Source File: filter_query.py    From houndsploit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def filter_shellcodes_without_comparator(shellcode, num_version, software_name, final_result_set):
    """
    Add the shellcode (without comparator) to the final_result_set if respect the condition set by the user.
    :param shellcode: the shellcode we have to check if it has a number of version that matches the value passed by
                        the user.
    :param num_version: the number of version searched by the user.
    :param software_name: the name of the software searched by the user.
    :param final_result_set: the result set that
    :return: the result set that
    """
    if not shellcode.description.__contains__('.x'):
        # exclude the exploit from results table if the number of version is not equal and contains 'x'
        try:
            if parse_version(num_version) == parse_version(get_num_version(software_name, shellcode.description)):
                final_result_set.append(shellcode)
        except TypeError:
            pass
    else:
        # exclude the exploit from results table if the number of version is not equal and not contains 'x'
        try:
            if is_equal_with_x(num_version, get_num_version(software_name, shellcode.description)):
                final_result_set.append(shellcode)
        except TypeError:
            pass
    return final_result_set 
Example #18
Source File: filter_query.py    From houndsploit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def filter_shellcodes_with_comparator_and_without_x(shellcode, num_version, software_name, final_result_set):
    """
    Add the shellcode (with comparator and without x) to the final_result_set if respect the condition set by the user.
    :param shellcode: the shellcode we have to check if it has a number of version that matches the value passed by
                        the user.
    :param num_version: the number of version searched by the user.
    :param software_name: the name of the software searched by the user.
    :param final_result_set: the result set that
    :return: the result set that
    """
    if str_contains_num_version_range(str(shellcode.description)):
        if is_in_version_range(num_version, software_name, shellcode.description):
            final_result_set.append(shellcode)
    else:
        try:
            if parse_version(num_version) <= parse_version(
                    get_num_version_with_comparator(software_name, shellcode.description)):
                final_result_set.append(shellcode)
        except TypeError:
            pass
    return final_result_set 
Example #19
Source File: setup.py    From pulse2percept with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_cython_status():
    """
    Returns a dictionary containing a boolean specifying whether Cython is
    up-to-date, along with the version string (empty string if not installed).
    """
    cython_status = {}
    try:
        import Cython
        from Cython.Build import cythonize
        cython_version = Cython.__version__
        cython_status['up_to_date'] = parse_version(
            cython_version) >= parse_version(CYTHON_MIN_VERSION)
        cython_status['version'] = cython_version
    except ImportError:
        traceback.print_exc()
        cython_status['up_to_date'] = False
        cython_status['version'] = ""
    return cython_status 
Example #20
Source File: hooks.py    From bobtemplates.odoo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def post_render_addon(configurator):
    variables = configurator.variables
    if variables["addon.oca"]:
        _rm_suffix(".oca", configurator, variables["addon.name"] + "/README.rst.oca")
        _rm_suffix(
            ".oca",
            configurator,
            variables["addon.name"] + "/static/description/icon.png.oca",
        )
    else:
        _delete_file(configurator, variables["addon.name"] + "/README.rst.oca")
        _delete_file(
            configurator, variables["addon.name"] + "/static/description/icon.png.oca"
        )
    version = variables["addon.version"]
    if parse_version(version) >= parse_version("10.0"):
        manifest_file = os.path.join(
            configurator.target_directory, variables["addon.name"] + "/__openerp__.py"
        )
        manifest_new_file = os.path.join(
            configurator.target_directory, variables["addon.name"] + "/__manifest__.py"
        )
        os.rename(manifest_file, manifest_new_file)
    # show message if any
    show_message(configurator)


#
# test hooks
# 
Example #21
Source File: git.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def _get_highest_tag(tags):
    """Find the highest tag from a list.

    Pass in a list of tag strings and this will return the highest
    (latest) as sorted by the pkg_resources version parser.
    """
    return max(tags, key=pkg_resources.parse_version) 
Example #22
Source File: install.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_version(version):
    """Use parse_version from pkg_resources or distutils as available."""
    global parse_version
    try:
        from pkg_resources import parse_version
    except ImportError:
        from distutils.version import LooseVersion as parse_version
    return parse_version(version) 
Example #23
Source File: install.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def _sort_key(self):
        return (self.parsed_filename.group('name'),
                parse_version(self.parsed_filename.group('ver')),
                tuple(-x for x in self.rank),
                self.filename) 
Example #24
Source File: install.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def parse_version(version):
    """Use parse_version from pkg_resources or distutils as available."""
    global parse_version
    try:
        from pkg_resources import parse_version
    except ImportError:
        from distutils.version import LooseVersion as parse_version
    return parse_version(version) 
Example #25
Source File: check.py    From slpkg with GNU General Public License v3.0 5 votes vote down vote up
def pkg_upgrade(repo, skip, flag):
    """Checking packages for upgrade
    """
    msg = Msg()
    msg.checking()
    PACKAGES_TXT = RepoInit(repo).fetch()[0]
    pkgs_for_upgrade = []
    # name = data[0]
    # location = data[1]
    # size = data[2]
    # unsize = data[3]
    data = repo_data(PACKAGES_TXT, repo, flag="")
    for pkg in installed():
        inst_pkg = split_package(pkg)
        for name in data[0]:
            if name:    # this tips because some pkg_name is empty
                repo_pkg = split_package(name[:-4])
            if (repo_pkg[0] == inst_pkg[0] and
                parse_version(repo_pkg[1]) > parse_version(inst_pkg[1]) and
                repo_pkg[3] >= inst_pkg[3] and
                    inst_pkg[0] not in skip and
                    repo_pkg[1] != "blacklist"):
                pkgs_for_upgrade.append(repo_pkg[0])
    msg.done()
    if "--checklist" in flag:
        pkgs_for_upgrade = choose_upg(pkgs_for_upgrade)
    return pkgs_for_upgrade 
Example #26
Source File: install.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def __lt__(self, other):
        if self.context != other.context:
            raise TypeError("{0}.context != {1}.context".format(self, other))

        return self._sort_key < other._sort_key

        # XXX prune

        sn = self.parsed_filename.group('name')
        on = other.parsed_filename.group('name')
        if sn != on:
            return sn < on
        sv = parse_version(self.parsed_filename.group('ver'))
        ov = parse_version(other.parsed_filename.group('ver'))
        if sv != ov:
            return sv < ov
        # Compatibility
        if self.context != other.context:
            raise TypeError("{0}.context != {1}.context".format(self, other))
        sc = self.rank
        oc = other.rank
        if sc != None and oc != None and sc != oc:
            # Smaller compatibility ranks are "better" than larger ones,
            # so we have to reverse the sense of the comparison here!
            return sc > oc
        elif sc == None and oc != None:
            return False
        return self.filename < other.filename 
Example #27
Source File: install.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _sort_key(self):
        return (self.parsed_filename.group('name'),
                parse_version(self.parsed_filename.group('ver')),
                tuple(-x for x in self.rank),
                self.filename) 
Example #28
Source File: install.py    From slpkg with GNU General Public License v3.0 5 votes vote down vote up
def not_downgrade(self, package):
        """Don't downgrade packages if repository version is lower than
        installed"""
        name = split_package(package)[0]
        rep_ver = split_package(package)[1]
        ins_ver = GetFromInstalled(name).version()[1:]
        if not ins_ver:
            ins_ver = "0"
        if parse_version(rep_ver) < parse_version(ins_ver):
            self.msg.template(78)
            print(f"| Package {name} don't downgrade, setting by user")
            self.msg.template(78)
            return True 
Example #29
Source File: install.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __lt__(self, other):
        if self.context != other.context:
            raise TypeError("{0}.context != {1}.context".format(self, other))

        return self._sort_key < other._sort_key

        # XXX prune

        sn = self.parsed_filename.group('name')
        on = other.parsed_filename.group('name')
        if sn != on:
            return sn < on
        sv = parse_version(self.parsed_filename.group('ver'))
        ov = parse_version(other.parsed_filename.group('ver'))
        if sv != ov:
            return sv < ov
        # Compatibility
        if self.context != other.context:
            raise TypeError("{0}.context != {1}.context".format(self, other))
        sc = self.rank
        oc = other.rank
        if sc != None and oc != None and sc != oc:
            # Smaller compatibility ranks are "better" than larger ones,
            # so we have to reverse the sense of the comparison here!
            return sc > oc
        elif sc == None and oc != None:
            return False
        return self.filename < other.filename 
Example #30
Source File: base.py    From lambda-chef-node-cleanup with Apache License 2.0 5 votes vote down vote up
def __init__(cls, name, bases, d):
        super(ChefObjectMeta, cls).__init__(name, bases, d)
        if name != 'ChefObject':
            ChefObject.types[name.lower()] = cls
        cls.api_version_parsed = pkg_resources.parse_version(cls.api_version)