Python semantic_version.Version() Examples

The following are 30 code examples of semantic_version.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 semantic_version , or try the search function .
Example #1
Source File: models.py    From appstore with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_compatible(self, platform_version, inclusive=False):
        """Checks if a release is compatible with a platform version

        :param platform_version: the platform version, not required to be
                                 semver compatible
        :param inclusive: if True the check will also return True if an app
                          requires 9.0.1 and the given platform version is 9.0
        :return: True if compatible, otherwise false
        """

        min_version = Version(pad_min_version(platform_version))
        spec = Spec(self.platform_version_spec)
        if inclusive:
            max_version = Version(pad_max_inc_version(platform_version))
            return (min_version in spec or max_version in spec)
        else:
            return min_version in spec 
Example #2
Source File: install.py    From py-solc-x with MIT License 6 votes vote down vote up
def set_solc_version_pragma(pragma_string, silent=False, check_new=False):
    version = _select_pragma_version(
        pragma_string, [Version(i[1:]) for i in get_installed_solc_versions()]
    )
    if not version:
        raise SolcNotInstalled(
            "No compatible solc version installed. "
            + "Use solcx.install_solc_version_pragma('{}') to install.".format(version)
        )
    version = _check_version(version)
    global solc_version
    solc_version = version
    if not silent:
        LOGGER.info("Using solc version {}".format(solc_version))
    if check_new:
        latest = install_solc_pragma(pragma_string, False)
        if Version(latest) > Version(version[1:]):
            LOGGER.info("Newer compatible solc version exists: {}".format(latest)) 
Example #3
Source File: test_utils.py    From release-bot with GNU General Public License v3.0 6 votes vote down vote up
def test_process_version_from_title():
    """Test converting title into version as per SemVer versioning"""
    latest_version = Version("0.0.1")

    title = '3.7.8 release'
    match, version = process_version_from_title(title, latest_version)
    assert version == "3.7.8"
    assert match is True
    title = 'new major release'
    match, version = process_version_from_title(title, latest_version)
    assert version == "1.0.0"
    assert match is True
    title = 'new minor release'
    match, version = process_version_from_title(title, latest_version)
    assert version == "0.1.0"
    assert match is True
    title = 'new patch release'
    match, version = process_version_from_title(title, latest_version)
    assert version == "0.0.2"
    assert match is True
    title = 'random release'
    match, version = process_version_from_title(title, latest_version)
    assert version == ""
    assert match is False 
Example #4
Source File: main.py    From brownie with MIT License 6 votes vote down vote up
def _compare_build_json(self, contract_name: str) -> bool:
        config = self._compiler_config
        # confirm that this contract was previously compiled
        try:
            source = self._sources.get(contract_name)
            build_json = self._build.get(contract_name)
        except KeyError:
            return True
        # compare source hashes
        if build_json["sha1"] != sha1(source.encode()).hexdigest():
            return True
        # compare compiler settings
        if _compare_settings(config, build_json["compiler"]):
            return True
        if build_json["language"] == "Solidity":
            # compare solc-specific compiler settings
            solc_config = config["solc"].copy()
            solc_config["remappings"] = None
            if _compare_settings(solc_config, build_json["compiler"]):
                return True
            # compare solc pragma against compiled version
            if Version(build_json["compiler"]["version"]) not in get_pragma_spec(source):
                return True
        return False 
Example #5
Source File: platformops.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def resolve_custom_platform_version(
        custom_platforms,
        selected_platform_name
):
    version_to_arn_mappings = generate_version_to_arn_mappings(
        custom_platforms,
        selected_platform_name
    )

    custom_platform_versions = []
    for custom_platform_version in version_to_arn_mappings.keys():
        custom_platform_versions.append(Version(custom_platform_version))

    if len(custom_platform_versions) > 1:
        chosen_custom_platform_arn = prompt_customer_for_custom_platform_version(
            version_to_arn_mappings
        )
    else:
        chosen_custom_platform_arn = custom_platforms[0]

    return PlatformVersion(chosen_custom_platform_arn) 
Example #6
Source File: conductor.py    From pros-cli2 with Mozilla Public License 2.0 6 votes vote down vote up
def register(cfg, location, kernel):
    first_run(cfg)
    kernel_version = kernel
    if kernel_version == 'latest':
        templates = local.get_local_templates(pros_cfg=cfg.pros_cfg,
                                              template_types=[TemplateTypes.kernel])  # type: List[Identifier]
        if not templates or len(templates) == 0:
            click.echo('No templates have been downloaded! Use `pros conduct download` to download the latest kernel or'
                       ' specify a kernel manually.')
            click.get_current_context().abort()
            sys.exit()
        kernel_version = sorted(templates, key=lambda t: semver.Version(t.version))[-1].version
        proscli.utils.debug('Resolved version {} to {}'.format(kernel, kernel_version))

    cfg = prosconfig.ProjectConfig(location, create=True, raise_on_error=True)
    cfg.kernel = kernel_version
    if not location:
        click.echo('Location not specified, registering current directory.')
    click.echo('Registering {} with kernel {}'.format(location or os.path.abspath('.'), kernel_version))
    cfg.save()


# endregion 
Example #7
Source File: util.py    From starfish with MIT License 5 votes vote down vote up
def __init__(self, doc: Optional[dict] = None, version: Optional[Version] = None):
        super(CodebookValidator, self).__init__(get_schema_path("codebook", doc, version)) 
Example #8
Source File: caching.py    From appstore with GNU Affero General Public License v3.0 5 votes vote down vote up
def nextcloud_release_etag(request: Any) -> str:
    releases = [Version(rel.version) for rel in NextcloudRelease.objects.all()]
    release_num = len(releases)
    if release_num > 0:
        latest_release = str(max(releases))
    else:
        latest_release = ''
    return '%d-%s' % (release_num, latest_release) 
Example #9
Source File: github.py    From appstore with GNU Affero General Public License v3.0 5 votes vote down vote up
def sync_releases(versions: Iterable[str]) -> None:
    """
    All given versions have a release. If a release is absent, persisted
    releases are out of date and need to have their release flag removed.
    Finally the latest version must be marked as current.
    :param versions: an iterable yielding all retrieved GitHub tags
    :return:
    """
    current_releases = NextcloudRelease.objects.all()
    imported_releases = [
        NextcloudRelease.objects.get_or_create(version=version)[0]
        for version in versions
    ]
    if imported_releases:
        # all imported releases have a release, existing ones don't
        for release in imported_releases:
            release.is_supported = True
            release.has_release = True
            release.save()
        for release in get_old_releases(current_releases, imported_releases):
            release.is_supported = False
            release.save()
        # set latest release
        NextcloudRelease.objects.update(is_current=False)
        latest = max(imported_releases, key=lambda v: Version(v.version))
        latest.is_current = True
        latest.save() 
Example #10
Source File: github.py    From appstore with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_stable(release: str) -> bool:
    try:
        version = Version(release)
        return not version.prerelease
    except ValueError:
        return False 
Example #11
Source File: sort_by_version.py    From appstore with GNU Affero General Public License v3.0 5 votes vote down vote up
def sort_by_version(value, arg):
    reverse = True if arg == 'desc' else False
    ret_list = []
    for key in sorted(value.keys(), reverse=reverse,
                      key=lambda v: Version(pad_min_version(v))):
        ret_list.append((key, value[key]))
    return ret_list 
Example #12
Source File: dockerver.py    From quay with Apache License 2.0 5 votes vote down vote up
def docker_version(user_agent_string):
    """
    Extract the Docker version from the user agent, taking special care to handle the case of a 1.5
    client requesting an auth token, which sends a broken user agent.

    If we can not positively identify a version, return None.
    """

    # First search for a well defined semver portion in the UA header.
    found_semver = _USER_AGENT_SEARCH_REGEX.search(user_agent_string)
    if found_semver:
        # Docker changed their versioning scheme on Feb 17, 2017 to use date-based versioning:
        # https://github.com/docker/docker/pull/31075

        # This scheme allows for 0s to appear as prefixes in the major or minor portions of the version,
        # which violates semver. Strip them out.
        portions = found_semver.group(1).split(".")
        updated_portions = [(p[:-1].lstrip("0") + p[-1]) for p in portions]
        return Version(".".join(updated_portions), partial=True)

    # Check if we received the very specific header which represents a 1.5 request
    # to the auth endpoints.
    elif _EXACT_1_5_USER_AGENT.match(user_agent_string):
        return Version(_ONE_FIVE_ZERO)

    else:
        return None 
Example #13
Source File: test_dockerver.py    From quay with Apache License 2.0 5 votes vote down vote up
def test_specs(spec, no_match_cases, match_cases):
    for no_match_case in no_match_cases:
        assert not spec.match(Version(no_match_case))

    for match_case in match_cases:
        assert spec.match(Version(match_case)) 
Example #14
Source File: codebook.py    From starfish with MIT License 5 votes vote down vote up
def _verify_version(cls, semantic_version_str: str) -> None:
        version = Version(semantic_version_str)
        if not (MIN_SUPPORTED_VERSION <= version <= MAX_SUPPORTED_VERSION):
            raise ValueError(
                f"version {version} not supported.  This version of the starfish library only "
                f"supports codebook formats from {MIN_SUPPORTED_VERSION} to "
                f"{MAX_SUPPORTED_VERSION}") 
Example #15
Source File: label_image.py    From starfish with MIT License 5 votes vote down vote up
def open_netcdf(cls, path: Union[str, Path]) -> "LabelImage":
        """Load a label image saved as a netcdf file from disk.

        Parameters
        ----------
        path : Union[str, Path]
            Path of the label image to instantiate from.

        Returns
        -------
        label_image : LabelImage
            Label image from the path.
        """
        label_image = xr.open_dataarray(path)
        if (
                AttrKeys.DOCTYPE not in label_image.attrs
                or label_image.attrs[AttrKeys.DOCTYPE] != DOCTYPE_STRING
                or AttrKeys.VERSION not in label_image.attrs
        ):
            raise ValueError(f"{path} does not appear to be a starfish label image")
        if not (
                MIN_SUPPORTED_VERSION
                <= Version(label_image.attrs[AttrKeys.VERSION])
                <= MAX_SUPPORTED_VERSION):
            raise ValueError(
                f"{path} contains a label image, but the version "
                f"{label_image.attrs[AttrKeys.VERSION]} is not supported")

        return cls(label_image) 
Example #16
Source File: util.py    From starfish with MIT License 5 votes vote down vote up
def __init__(self, doc: Optional[dict] = None, version: Optional[Version] = None):
        super(ManifestValidator, self).__init__(get_schema_path("fov_manifest", doc, version)) 
Example #17
Source File: transforms_list.py    From starfish with MIT License 5 votes vote down vote up
def _verify_version(cls, semantic_version_str: str) -> None:
        version = Version(semantic_version_str)
        if not (MIN_SUPPORTED_VERSION <= version <= MAX_SUPPORTED_VERSION):
            raise ValueError(
                f"version {version} not supported.  This version of the starfish library only "
                f"supports transform list formats from {MIN_SUPPORTED_VERSION} to "
                f"{MAX_SUPPORTED_VERSION}") 
Example #18
Source File: experiment.py    From starfish with MIT License 5 votes vote down vote up
def verify_version(cls, semantic_version_str: str) -> Version:
        """Verifies the compatibility of the current starfish version with
        the experiment version"""
        version = Version(semantic_version_str)
        if not (MIN_SUPPORTED_VERSION <= version <= MAX_SUPPORTED_VERSION):
            raise ValueError(
                f"version {version} not supported.  This version of the starfish library only "
                f"supports formats from {MIN_SUPPORTED_VERSION} to "
                f"{MAX_SUPPORTED_VERSION}")
        return version 
Example #19
Source File: versioning.py    From appstore with GNU Affero General Public License v3.0 5 votes vote down vote up
def version_in_spec(version: str, spec: str) -> bool:
    """
    Checks if a string version is in a spec
    :param version:
    :param spec:
    :return:
    """
    return Version(version) in Spec(spec) 
Example #20
Source File: views.py    From appstore with GNU Affero General Public License v3.0 5 votes vote down vote up
def _sort_by_platform_v(self, releases_by_platform, reverse=True):
        """Sorts a list of tuples like (<platform version>, [releases]) by
        platform version.

        :param releases_by_platform: A list of tuples.
        :param reverse: Descending order if True, ascending otherwise.
        :return sorted list of tuples.
        """

        return sorted(releases_by_platform, reverse=reverse,
                      key=lambda v: Version(pad_min_version(v[0]))) 
Example #21
Source File: pre_parser.py    From vyper with Apache License 2.0 5 votes vote down vote up
def validate_version_pragma(version_str: str, start: ParserPosition) -> None:
    """
    Validates a version pragma directive against the current compiler version.
    """
    from vyper import __version__

    version_arr = version_str.split("@version")

    raw_file_version = version_arr[1].strip()
    strict_file_version = _convert_version_str(raw_file_version)
    strict_compiler_version = Version(_convert_version_str(__version__))

    if len(strict_file_version) == 0:
        raise VersionException(
            "Version specification cannot be empty", start,
        )

    try:
        npm_spec = NpmSpec(strict_file_version)
    except ValueError:
        raise VersionException(
            f'Version specification "{raw_file_version}" is not a valid NPM semantic '
            f"version specification",
            start,
        )

    if not npm_spec.match(strict_compiler_version):
        raise VersionException(
            f'Version specification "{raw_file_version}" is not compatible '
            f'with compiler version "{__version__}"',
            start,
        )


# compound statements that are replaced with `class` 
Example #22
Source File: ambscout.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def get_semver(version_string: str) -> Optional[semantic_version.Version]:
        semver = None

        try:
            semver = semantic_version.Version(version_string)
        except ValueError:
            pass

        return semver 
Example #23
Source File: ambscout.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def __init__(self, install_id=None, update_frequency=datetime.timedelta(hours=12), local_only=False) -> None:
        if not install_id:
            install_id = os.environ.get('AMBASSADOR_CLUSTER_ID',
                                        os.environ.get('AMBASSADOR_SCOUT_ID', "00000000-0000-0000-0000-000000000000"))

        self.install_id = install_id
        self.runtime = "kubernetes" if os.environ.get('KUBERNETES_SERVICE_HOST', None) else "docker"
        self.namespace = os.environ.get('AMBASSADOR_NAMESPACE', 'default')

        self.is_edge_stack = os.path.exists('/ambassador/.edge_stack')
        self.app = "aes" if self.is_edge_stack else "ambassador"
        self.version = Version if self.is_edge_stack else self.parse_git_description(Version, Build)
        self.semver = self.get_semver(self.version)

        self.logger = logging.getLogger("ambassador.scout")
        # self.logger.setLevel(logging.DEBUG)

        self.logger.debug("Ambassador version %s built from %s on %s" % (Version, Build.git.commit, Build.git.branch))
        self.logger.debug("Scout version      %s%s" % (self.version, " - BAD SEMVER" if not self.semver else ""))
        self.logger.debug("Runtime            %s" % self.runtime)
        self.logger.debug("Namespace          %s" % self.namespace)

        self._scout = None
        self._scout_error = None

        self._local_only = local_only

        self._notices = None
        self._last_result = None
        self._update_frequency = update_frequency
        self._latest_version = None
        self._latest_semver = None

        self.reset_cache_time() 
Example #24
Source File: store.py    From ftcommunity-TXT with GNU General Public License v3.0 5 votes vote down vote up
def format(id):
        # map app key to human readable text.
        labels = { "version":  QCoreApplication.translate("AppInfo", "Version"),
                   "desc":     QCoreApplication.translate("AppInfo", "Description"),
                   "author":   QCoreApplication.translate("AppInfo", "Author"),
                   "firmware": QCoreApplication.translate("AppInfo", "Firmware"),
                   "set":      QCoreApplication.translate("AppInfo", "Set"),
                   "model":    QCoreApplication.translate("AppInfo", "Model"),
                   "category": QCoreApplication.translate("AppInfo", "Category"),
                   "depends":  QCoreApplication.translate("AppInfo", "Dependencies")
               }
        if id in labels:
            return labels[id]
        else:
            return None 
Example #25
Source File: store.py    From ftcommunity-TXT with GNU General Public License v3.0 5 votes vote down vote up
def format(id):
        # map app key to human readable text.
        labels = { "version":  QCoreApplication.translate("AppInfo", "Version"),
                   "desc":     QCoreApplication.translate("AppInfo", "Description"),
                   "author":   QCoreApplication.translate("AppInfo", "Author"),
                   "firmware": QCoreApplication.translate("AppInfo", "Firmware"),
                   "set":      QCoreApplication.translate("AppInfo", "Set"),
                   "model":    QCoreApplication.translate("AppInfo", "Model"),
                   "category": QCoreApplication.translate("AppInfo", "Category"),
                   "depends":  QCoreApplication.translate("AppInfo", "Dependencies")
               }
        if id in labels:
            return labels[id]
        else:
            return None 
Example #26
Source File: test_common.py    From pylti with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_version():
        """
        Will raise ValueError if not a semantic version
        """
        semantic_version.Version(pylti.__version__) 
Example #27
Source File: model_factory.py    From margipose with Apache License 2.0 5 votes vote down vote up
def is_for(self, model_type: str, version: Version):
        """Check if this factory is responsible for the given model type and version."""
        return model_type == self.model_type and version in self.version_spec 
Example #28
Source File: __init__.py    From margipose with Apache License 2.0 5 votes vote down vote up
def create_model(model_desc):
    type_name = model_desc['type']
    version = Version(model_desc['version'])

    for factory in MODEL_FACTORIES:
        if factory.is_for(type_name, version):
            model = factory.create(model_desc)
            break
    else:
        raise Exception('unrecognised model {} v{}'.format(type_name, str(version)))

    return model 
Example #29
Source File: item.py    From dtf with Apache License 2.0 5 votes vote down vote up
def __repr__(self):

        """Tostring for item"""

        temp = "Name: %s (%s)\n" % (self.name, self.type)
        if self.type == TYPE_MODULE:
            temp += "  About: %s\n" % self.about
        temp += "  Installs as: %s\n" % self.install_name
        temp += "  Author: %s\n" % self.author
        temp += "  Version: %s\n" % self.version
        return temp 
Example #30
Source File: item.py    From dtf with Apache License 2.0 5 votes vote down vote up
def item_is_newer(installed_item, item):

    """Determine if an item is newer"""

    return bool(semantic_version.Version(installed_item.version) <
                semantic_version.Version(item.version))