Python packaging.version.LegacyVersion() Examples

The following are 13 code examples of packaging.version.LegacyVersion(). 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 packaging.version , or try the search function .
Example #1
Source File: msvc.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def msvc14_gen_lib_options(*args, **kwargs):
    """
    Patched "distutils._msvccompiler.gen_lib_options" for fix
    compatibility between "numpy.distutils" and "distutils._msvccompiler"
    (for Numpy < 1.11.2)
    """
    if "numpy.distutils" in sys.modules:
        import numpy as np
        if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):
            return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)
    return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs) 
Example #2
Source File: version.py    From AnyBlok with Mozilla Public License 2.0 5 votes vote down vote up
def parse_other(self, other):
        if other is None:
            other = LegacyVersion('')
        elif not isinstance(other, (Version, LegacyVersion)):
            other = parse_version(other)

        return other 
Example #3
Source File: versions.py    From addon-check with GNU General Public License v3.0 5 votes vote down vote up
def _islegacy_devversion(self):
        return isinstance(self.version, LegacyVersion) and \
            ("~beta" or "~alpha" in self.version) 
Example #4
Source File: msvc.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def msvc14_gen_lib_options(*args, **kwargs):
    """
    Patched "distutils._msvccompiler.gen_lib_options" for fix
    compatibility between "numpy.distutils" and "distutils._msvccompiler"
    (for Numpy < 1.11.2)
    """
    if "numpy.distutils" in sys.modules:
        import numpy as np
        if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):
            return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)
    return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs) 
Example #5
Source File: cve_lookup.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def find_matching_cpe_product(cpe_matches: List[Product], requested_version: str) -> Product:
    if requested_version.isdigit() or is_valid_dotted_version(requested_version):
        version_numbers = [t.version_number for t in cpe_matches]
        if requested_version in version_numbers:
            return find_cpe_product_with_version(cpe_matches, requested_version)
        version_numbers.append(requested_version)
        version_numbers.sort(key=lambda v: LegacyVersion(parse(v)))
        next_closest_version = find_next_closest_version(version_numbers, requested_version)
        return find_cpe_product_with_version(cpe_matches, next_closest_version)
    if requested_version == 'ANY':
        return find_cpe_product_with_version(cpe_matches, 'ANY')
    logging.warning('Version returned from CPE match has invalid type. Returned CPE might not contain relevant version number')
    return cpe_matches[0] 
Example #6
Source File: cves.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def get_base_release(full_ver):
        # if LegacyVersion, converting manually to a base version
        if isinstance(full_ver, version.LegacyVersion):
            return version.parse(".".join(full_ver._version.split(".")[:2]))
        return version.parse(".".join(map(str, full_ver._version.release[:2]))) 
Example #7
Source File: cves.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def to_legacy(full_ver):
        # converting version to version.LegacyVersion
        return version.LegacyVersion(".".join(map(str, full_ver._version.release))) 
Example #8
Source File: cves.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def to_raw_version(v):
        if not isinstance(v, version.LegacyVersion):
            return ".".join(map(str, v._version.release))
        return v._version 
Example #9
Source File: cves.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def version_compare(v1, v2):
        """Function compares two versions, handling differences with conversion to LegacyVersion"""
        # getting raw version, while striping 'v' char at the start. if exists.
        # removing this char lets us safely compare the two version.
        v1_raw = CveUtils.to_raw_version(v1).strip("v")
        v2_raw = CveUtils.to_raw_version(v2).strip("v")
        new_v1 = version.LegacyVersion(v1_raw)
        new_v2 = version.LegacyVersion(v2_raw)

        return CveUtils.basic_compare(new_v1, new_v2) 
Example #10
Source File: cves.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def is_vulnerable(fix_versions, check_version, ignore_downstream=False):
        """Function determines if a version is vulnerable,
        by comparing to given fix versions by base release"""
        if ignore_downstream and CveUtils.is_downstream_version(check_version):
            return False

        vulnerable = False
        check_v = version.parse(check_version)
        base_check_v = CveUtils.get_base_release(check_v)

        # default to classic compare, unless the check_version is legacy.
        version_compare_func = CveUtils.basic_compare
        if isinstance(check_v, version.LegacyVersion):
            version_compare_func = CveUtils.version_compare

        if check_version not in fix_versions:
            # comparing ease base release for a fix
            for fix_v in fix_versions:
                fix_v = version.parse(fix_v)
                base_fix_v = CveUtils.get_base_release(fix_v)

                # if the check version and the current fix has the same base release
                if base_check_v == base_fix_v:
                    # when check_version is legacy, we use a custom compare func, to handle differences between versions
                    if version_compare_func(check_v, fix_v) == -1:
                        # determine vulnerable if smaller and with same base version
                        vulnerable = True
                        break

        # if we did't find a fix in the fix releases, checking if the version is smaller that the first fix
        if not vulnerable and version_compare_func(check_v, version.parse(fix_versions[0])) == -1:
            vulnerable = True

        return vulnerable 
Example #11
Source File: utils.py    From pythonfinder with MIT License 4 votes vote down vote up
def parse_python_version(version_str):
    # type: (str) -> Dict[str, Union[str, int, Version]]
    from packaging.version import parse as parse_version

    is_debug = False
    if version_str.endswith("-debug"):
        is_debug = True
        version_str, _, _ = version_str.rpartition("-")
    match = version_re.match(version_str)
    if not match:
        raise InvalidPythonVersion("%s is not a python version" % version_str)
    version_dict = match.groupdict()  # type: Dict[str, str]
    major = int(version_dict.get("major", 0)) if version_dict.get("major") else None
    minor = int(version_dict.get("minor", 0)) if version_dict.get("minor") else None
    patch = int(version_dict.get("patch", 0)) if version_dict.get("patch") else None
    is_postrelease = True if version_dict.get("post") else False
    is_prerelease = True if version_dict.get("prerel") else False
    is_devrelease = True if version_dict.get("dev") else False
    if patch:
        patch = int(patch)
    version = None  # type: Optional[Union[Version, LegacyVersion]]
    try:
        version = parse_version(version_str)
    except TypeError:
        version = None
    if isinstance(version, LegacyVersion) or version is None:
        v_dict = version_dict.copy()
        pre = ""
        if v_dict.get("prerel") and v_dict.get("prerelversion"):
            pre = v_dict.pop("prerel")
            pre = "{0}{1}".format(pre, v_dict.pop("prerelversion"))
        v_dict["pre"] = pre
        keys = ["major", "minor", "patch", "pre", "postdev", "post", "dev"]
        values = [v_dict.get(val) for val in keys]
        version_str = ".".join([str(v) for v in values if v])
        version = parse_version(version_str)
    return {
        "major": major,
        "minor": minor,
        "patch": patch,
        "is_postrelease": is_postrelease,
        "is_prerelease": is_prerelease,
        "is_devrelease": is_devrelease,
        "is_debug": is_debug,
        "version": version,
    } 
Example #12
Source File: utils.py    From pipenv with MIT License 4 votes vote down vote up
def parse_python_version(version_str):
    # type: (str) -> Dict[str, Union[str, int, Version]]
    from packaging.version import parse as parse_version

    is_debug = False
    if version_str.endswith("-debug"):
        is_debug = True
        version_str, _, _ = version_str.rpartition("-")
    match = version_re.match(version_str)
    if not match:
        raise InvalidPythonVersion("%s is not a python version" % version_str)
    version_dict = match.groupdict()  # type: Dict[str, str]
    major = int(version_dict.get("major", 0)) if version_dict.get("major") else None
    minor = int(version_dict.get("minor", 0)) if version_dict.get("minor") else None
    patch = int(version_dict.get("patch", 0)) if version_dict.get("patch") else None
    is_postrelease = True if version_dict.get("post") else False
    is_prerelease = True if version_dict.get("prerel") else False
    is_devrelease = True if version_dict.get("dev") else False
    if patch:
        patch = int(patch)
    version = None  # type: Optional[Union[Version, LegacyVersion]]
    try:
        version = parse_version(version_str)
    except TypeError:
        version = None
    if isinstance(version, LegacyVersion) or version is None:
        v_dict = version_dict.copy()
        pre = ""
        if v_dict.get("prerel") and v_dict.get("prerelversion"):
            pre = v_dict.pop("prerel")
            pre = "{0}{1}".format(pre, v_dict.pop("prerelversion"))
        v_dict["pre"] = pre
        keys = ["major", "minor", "patch", "pre", "postdev", "post", "dev"]
        values = [v_dict.get(val) for val in keys]
        version_str = ".".join([str(v) for v in values if v])
        version = parse_version(version_str)
    return {
        "major": major,
        "minor": minor,
        "patch": patch,
        "is_postrelease": is_postrelease,
        "is_prerelease": is_prerelease,
        "is_devrelease": is_devrelease,
        "is_debug": is_debug,
        "version": version,
    } 
Example #13
Source File: setup.py    From protect with Apache License 2.0 4 votes vote down vote up
def check_tool_version(tool, required_version, blacklisted_versions=None, binary=False):
    """
    This will ensure that the required_version of `tool` is at least `required_version`.
    :param str tool: The tool under review
    :param str required_version: The version of the tool required by ProTECT
    :param list blacklisted_versions: Version of the tool blacklisted by ProTECT
    :param bool binary: Is the tool a binary
    :return: None
    """
    if binary:
        try:
            installed_version = subprocess.check_output([tool, '--version'],
                                                        stderr=subprocess.STDOUT)
        except OSError as err:
            if err.errno == errno.ENOENT:
                raise RuntimeError('Is %s installed as a binary and present on your $PATH?' % tool)
            else:
                raise
        installed_version = installed_version.rstrip()
    else:
        try:
            module = __import__(tool + '.version')
        except ImportError:
            raise RuntimeError('Is %s installed as a library, and is it accessible in the same '
                               'environment as ProTECT?' % tool)
        try:
            installed_version = getattr(module, 'version').version
        except AttributeError:
            raise RuntimeError('Does %s have a version.py?' % tool)

    if type(parse_version(installed_version)) == _LegacyVersion:
        print('Detecting that the installed version of "%s"(%s) is probably based off a git commit '
              'and assuming this build is for testing purposes.  If this is not the case, please '
              'try again with a valid version of "%s".' % (tool, installed_version, tool))
    elif parse_version(installed_version) < parse_version(required_version):
        raise RuntimeError('%s was detected to be version (%s) but ProTECT requires (%s)' %
                           (tool, installed_version, required_version))
    if blacklisted_versions is not None:
        if parse_version(installed_version) in [parse_version(v) for v in blacklisted_versions]:
            raise RuntimeError('The version of %s was detected to be on the a blacklist (%s).' %
                               (tool, installed_version))


# Check Toil version