コード例 #1
0
def version_to_semantic_version(version):
    """
    Creates a semantic version from a numeric redis module version.
    """

    major = int(version / 10000)
    version -= major * 10000
    minor = int(version / 100)
    version -= minor * 100
    patch = int(version)

    sem_version_str = '{}.{}.{}'.format(major, minor, patch)
    # sem_version_str = '%02d.%02d.%02d' % (major, minor, patch)
    return semantic_version.Version(sem_version_str)
コード例 #2
0
    def test_register_package(self):
        test_version = semantic_version.Version('1.1.0')
        package = mock.MagicMock()
        package.name = 'test_package_name'
        package.version = test_version
        package.classes = ['test_class_1', 'test_class_2']

        self.loader.register_package(package)
        self.assertEqual(
            package,
            self.loader._package_cache['test_package_name'][test_version])
        for class_name in package.classes:
            self.assertEqual(
                package, self.loader._class_cache[class_name][test_version])
コード例 #3
0
    def __init__(self, version_string, url=None):
        ''' Wrap the semantic_version Version class so that we can represent
            'tip' versions as well as specific versions, and store an optional
            URL that can represent the location from which we can retrieve this
            version.

            Also add some useful methods for manipulating versions.
        '''
        super(Version, self).__init__()
        self.url = url
        version_string = str(version_string.strip())
        # strip of leading v or = characters, these are permitted in npm's
        # semver, and npm tags versions as v1.2.3
        self.version = None
        if version_string.startswith('v') or version_string.startswith('='):
            self.version = semantic_version.Version(version_string[1:],
                                                    partial=False)
        elif not version_string:
            self.version = TipVersion()
        else:
            self.version = semantic_version.Version(version_string,
                                                    partial=False)
        self.url = url
コード例 #4
0
class PkgRepoMixin(object):

    PIO_VERSION = semantic_version.Version(util.pepver_to_semver(__version__))

    @staticmethod
    def max_satisfying_repo_version(versions, requirements=None):
        item = None
        systype = util.get_systype()
        reqspec = None
        if requirements:
            try:
                reqspec = semantic_version.Spec(requirements)
            except ValueError:
                pass

        for v in versions:
            if "system" in v and v['system'] not in ("all", "*") and \
                    systype not in v['system']:
                continue
            if "platformio" in v.get("engines", {}):
                if PkgRepoMixin.PIO_VERSION not in semantic_version.Spec(
                        v['engines']['platformio']):
                    continue
            specver = semantic_version.Version(v['version'])
            if reqspec and specver not in reqspec:
                continue
            if not item or semantic_version.Version(item['version']) < specver:
                item = v
        return item

    def get_latest_repo_version(  # pylint: disable=unused-argument
            self,
            name,
            requirements,
            silent=False):
        version = None
        for versions in PackageRepoIterator(name, self.repositories):
            pkgdata = self.max_satisfying_repo_version(versions, requirements)
            if not pkgdata:
                continue
            if not version or semantic_version.compare(pkgdata['version'],
                                                       version) == 1:
                version = pkgdata['version']
        return version

    def get_all_repo_versions(self, name):
        result = []
        for versions in PackageRepoIterator(name, self.repositories):
            result.extend([v['version'] for v in versions])
        return sorted(set(result))
コード例 #5
0
def select_latest_version(input_version='0.0.0',
                          libio='0.0.0',
                          anitya='0.0.0'):
    libio_latest_version = convert_version_to_proper_semantic(libio)
    anitya_latest_version = convert_version_to_proper_semantic(anitya)
    input_version = convert_version_to_proper_semantic(input_version)

    try:
        latest_version = libio_latest_version
        return_version = libio
        if sv.SpecItem('<' + anitya_latest_version).match(
                sv.Version(libio_latest_version)):
            latest_version = anitya_latest_version
            return_version = anitya
        if sv.SpecItem('<' + input_version).match(sv.Version(latest_version)):
            # User provided version is higher. Do not show the latest version in the UI
            return_version = ''
    except ValueError:
        # In case of failure let's not show any latest version at all
        return_version = ''
        pass

    return return_version
コード例 #6
0
def get_db_stable_version():
    '''
    Returns the semantic DB stable version
    '''
    db = Database(creds=creds)
    df = db.send_query(
        """SELECT * FROM ModelMonitoring.metaData WHERE setting = 'stable_version';"""
    )
    db.close()
    db_stable_version = df.loc[0]['val']
    if db_stable_version:
        return semantic_version.Version(db_stable_version)
    else:
        return
コード例 #7
0
def new(cfg, kernel, location, depot, mode):
    first_run(cfg)
    templates = local.get_local_templates(pros_cfg=cfg.pros_cfg,
                                          template_types=[
                                              TemplateTypes.kernel
                                          ])  # type: Set[Identifier]
    if not templates or len(templates) == 0:
        click.echo(
            'No templates have been downloaded! Use `pros conduct download` to download the latest kernel.'
        )
        click.get_current_context().abort()
        sys.exit()
    kernel_version = kernel
    if kernel == 'latest':
        kernel_version = sorted(
            templates, key=lambda t: semver.Version(t.version))[-1].version
        proscli.utils.debug('Resolved version {} to {}'.format(
            kernel, kernel_version))
    templates = [t for t in templates
                 if t.version == kernel_version]  # type: List[Identifier]
    depot_registrar = depot
    if depot == 'auto':
        templates = [t for t in templates if t.version == kernel_version]
        if not templates or len(templates) == 0:
            click.echo('No templates exist for {}'.format(kernel_version))
            click.get_current_context().abort()
            sys.exit()
        if 'pros-mainline' in [t.depot for t in templates]:
            depot_registrar = 'pros-mainline'
        else:
            depot_registrar = [t.depot for t in templates][0]
        proscli.utils.debug('Resolved depot {} to {}'.format(
            depot, depot_registrar))
    templates = [t for t in templates if t.depot == depot_registrar]
    if not templates or len(templates) == 0:
        click.echo(
            'No templates were found for kernel version {} on {}'.format(
                kernel_version, depot_registrar))
        click.get_current_context().abort()
        sys.exit()
    template = templates[0]
    if not os.path.isabs(location):
        location = os.path.abspath(location)
    click.echo('Creating new project from {} on {} at {}'.format(
        template.version, template.depot, location))
    local.create_project(identifier=template,
                         dest=location,
                         pros_cli=cfg.pros_cfg,
                         require_empty=(mode == 'safe'),
                         overwrite=(mode == 'force'))
コード例 #8
0
    def _get_versions_in_repo(self, obj):
        repo_param = self.context['path']
        distro = AnsibleDistribution.objects.get(base_path=repo_param)
        repository_version = distro.repository.latest_version()
        collection_versions = CollectionVersion.objects.filter(
            collection=obj.collection)

        versions_in_repo = collection_versions.filter(
            pk__in=repository_version.content)
        versions_in_repo = sorted(
            versions_in_repo,
            key=lambda obj: semantic_version.Version(obj.version),
            reverse=True)
        return versions_in_repo
コード例 #9
0
    def max_satisfying_repo_version(self, versions, requirements=None):
        item = None
        reqspec = None
        try:
            reqspec = (
                semantic_version.SimpleSpec(requirements) if requirements else None
            )
        except ValueError:
            pass

        for v in versions:
            if not self.is_system_compatible(v.get("system")):
                continue
            # if "platformio" in v.get("engines", {}):
            #     if PkgRepoMixin.PIO_VERSION not in requirements.SimpleSpec(
            #             v['engines']['platformio']):
            #         continue
            specver = semantic_version.Version(v["version"])
            if reqspec and specver not in reqspec:
                continue
            if not item or semantic_version.Version(item["version"]) < specver:
                item = v
        return item
コード例 #10
0
ファイル: package.py プロジェクト: zeegates/platformio-core
    def max_satisfying_repo_version(self, versions, requirements=None):
        item = None
        reqspec = None
        if requirements:
            try:
                reqspec = self.parse_semver_spec(requirements,
                                                 raise_exception=True)
            except ValueError:
                pass

        for v in versions:
            if not self.is_system_compatible(v.get("system")):
                continue
            if "platformio" in v.get("engines", {}):
                if PkgRepoMixin.PIO_VERSION not in self.parse_semver_spec(
                        v['engines']['platformio'], raise_exception=True):
                    continue
            specver = semantic_version.Version(v['version'])
            if reqspec and specver not in reqspec:
                continue
            if not item or semantic_version.Version(item['version']) < specver:
                item = v
        return item
コード例 #11
0
ファイル: service.py プロジェクト: qingyufei/trove
    def get_backup_strategy(self):
        """Get backup strategy.

        innobackupex was removed in Percona XtraBackup 8.0, use xtrabackup
        instead.
        """
        strategy = cfg.get_configuration_property('backup_strategy')

        mysql_8 = semantic_version.Version('8.0.0')
        cur_ver = semantic_version.Version.coerce(CONF.datastore_version)
        if cur_ver >= mysql_8:
            strategy = 'xtrabackup'

        return strategy
コード例 #12
0
ファイル: views.py プロジェクト: fao89/pulp_ansible
    def get_queryset(self):
        """
        Returns a Collections queryset for specified distribution.
        """
        repo_version = self.get_repository_version(self.kwargs["path"])
        deprecated_query = AnsibleCollectionDeprecated.objects.filter(
            collection=OuterRef("pk"), repository_version=repo_version)
        collections = Collection.objects.filter(
            versions__in=repo_version.content).distinct()
        collections = collections.annotate(deprecated=Exists(deprecated_query))

        versions_qs = CollectionVersion.objects.filter(
            pk__in=repo_version.content).values_list(
                "collection_id",
                "namespace",
                "name",
                "version",
                "pulp_created",
            )

        highest_versions = defaultdict(lambda: CollectionTuple(
            None, None, semantic_version.Version("0.0.0"), None))
        lowest_versions = defaultdict(lambda: CollectionTuple(
            None, None, semantic_version.Version("100000000000.0.0"), None))
        for collection_id, namespace, name, version, pulp_created in versions_qs:
            version_to_consider = semantic_version.Version(version)
            collection_tuple = CollectionTuple(namespace, name,
                                               version_to_consider,
                                               pulp_created)
            if version_to_consider > highest_versions[collection_id].version:
                highest_versions[collection_id] = collection_tuple
            if version_to_consider < lowest_versions[collection_id].version:
                lowest_versions[collection_id] = collection_tuple

        self.highest_versions_context = highest_versions  # needed by get__serializer_context
        self.lowest_versions_context = lowest_versions  # needed by get__serializer_context
        return collections
コード例 #13
0
    def max_satisfying_repo_version(versions, requirements=None):

        def _cmp_dates(datestr1, datestr2):
            date1 = arrow.get(datestr1)
            date2 = arrow.get(datestr2)
            if date1 == date2:
                return 0
            return -1 if date1 < date2 else 1

        item = None
        reqspec = None
        if requirements:
            try:
                reqspec = semantic_version.Spec(requirements)
            except ValueError:
                pass
        for v in versions:
            specver = None
            try:
                specver = semantic_version.Version(v['name'], partial=True)
            except ValueError:
                pass

            if reqspec:
                if not specver or specver not in reqspec:
                    continue
                if not item or semantic_version.Version(
                        item['name'], partial=True) < specver:
                    item = v
            elif requirements:
                if requirements == v['name']:
                    return v
            else:
                if not item or _cmp_dates(item['released'],
                                          v['released']) == -1:
                    item = v
        return item
コード例 #14
0
def test_convert_caret_specification():
    spec = ">=1.1.2"
    assert et_micc.utils.convert_caret_specification(spec) == spec
    spec = "^1.1.2"
    spec_new = et_micc.utils.convert_caret_specification(spec)
    assert spec_new == ">=1.1.2,<2.0.0"
    assert     sv.SimpleSpec("1.1.2").match(sv.Version("1.1.2"))
    assert not sv.Version("1.1.1") in sv.SimpleSpec(spec_new)
    assert     sv.Version("1.1.2") in sv.SimpleSpec(spec_new)
    assert     sv.Version("1.1.2") in sv.SimpleSpec(spec_new)
    assert     sv.Version("1.2.2") in sv.SimpleSpec(spec_new)
    assert not sv.Version("2.0.0") in sv.SimpleSpec(spec_new)
    assert not sv.Version("2.2.2") in sv.SimpleSpec(spec_new)
コード例 #15
0
ファイル: sql_query.py プロジェクト: qingyufei/trove
    def __str__(self):
        if self.ds == 'mysql':
            cur_version = semantic_version.Version.coerce(self.ds_version)
            mysql_575 = semantic_version.Version('5.7.5')
            if cur_version <= mysql_575:
                return (f"SET PASSWORD FOR '{self.user}'@'{self.host}' = "
                        f"PASSWORD('{self.new_password}');")

            return (f"ALTER USER '{self.user}'@'{self.host}' "
                    f"IDENTIFIED WITH mysql_native_password "
                    f"BY '{self.new_password}';")
        elif self.ds == 'mariadb':
            return (f"ALTER USER '{self.user}'@'{self.host}' IDENTIFIED VIA "
                    f"mysql_native_password USING "
                    f"PASSWORD('{self.new_password}');")
コード例 #16
0
def increment_version(version_type):
    version_number = get_version()
    version = semantic_version.Version(version_number, partial=True)
    if version_type == 'major':
        new_version = version.next_major()
    elif version_type == 'minor':
        new_version = version.next_minor()
    elif version_type == 'patch':
        new_version = version.next_patch()
    else:
        print('Valid versions are {}, {}, {}'.format(*VERSION_TYPES))
        sys.exist(1)

    with open(VERSION_FILE, 'wb') as version_file:
        version_file.write("__version__ = '{}'\n".format(new_version))
コード例 #17
0
ファイル: test_cli_core.py プロジェクト: j9ac9k/NavitronEve
def test_generate_metadata():
    """validate expected behavior for cli_core.append_metadata()"""
    data = cli_core.generate_metadata('test', '0.0.0')

    # Validate types
    assert isinstance(data, dict)
    assert semantic_version.Version(data['version'])
    assert semantic_version.Version(data['package_version'])
    assert uuid.UUID(data['write_recipt'])
    assert dateutil.parser.parse(data['cron_datetime'])

    # Validate expected contents
    expected_headers = [
        'write_recipt', 'data_source', 'machine_source', 'version',
        'package_version', 'cron_datetime'
    ]

    unique_values, unique_expected = helpers.find_uniques(
        list(data.keys()), expected_headers)

    assert unique_expected == []
    if unique_values:
        pytest.xfail('Unexpected values from append_metadata(): {}'.format(
            unique_values))
コード例 #18
0
ファイル: lint.py プロジェクト: maxamillion/ansibulled
    def check_version(self, version: str, message: str) -> Optional[semantic_version.Version]:
        """
        Check that the given version is a valid semantic version.

        :arg version: Version string to check
        :arg message: Message to prepend to error
        :return: A ``semantic_version.Version`` object
        """
        try:
            return semantic_version.Version(version)
        except ValueError as exc:
            self.errors.append((self.path, 0, 0,
                                '{0}: error while parse version "{1}": {2}'
                                .format(message, version, exc)))
            return None
コード例 #19
0
def cluster_info(data: dict, op_ctx: ctx.OperationContext):
    """Request handler for cluster info operation.

    Required data: cluster_name
    Optional data and default values: org_name=None, ovdc_name=None

    (data validation handled in broker)

    :return: Dict
    """
    rde_in_use = server_utils.get_rde_version_in_use()

    # Redirect to generic handler if the backend supports RDE-2.0
    if semantic_version.Version(rde_in_use) >= semantic_version.Version(
            rde_constants.RDEVersion.RDE_2_0_0.value):  # noqa: E501
        rde_data: dict = cluster_handler.cluster_info(data=data, op_ctx=op_ctx)
        new_rde = common_models.DefEntity(**rde_data)
    else:
        svc = cluster_service_factory.ClusterServiceFactory(
            op_ctx).get_cluster_service(rde_in_use)  # noqa: E501
        cluster_id = data[RequestKey.CLUSTER_ID]
        new_rde = svc.get_cluster_info(cluster_id)

    return _convert_rde_to_1_0_format(new_rde.to_dict())
コード例 #20
0
    def list(self, request, *args, **kwargs):
        """Override drf ListModelMixin to sort versions by semver."""
        queryset = self.filter_queryset(self.get_queryset())

        data = sorted(queryset,
                      key=lambda x: semantic_version.Version(x.version),
                      reverse=True)

        page = self.paginate_queryset(data)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
コード例 #21
0
def find_contours(mask):
	result = cv2.findContours(
		mask.astype(np.uint8),
		cv2.RETR_EXTERNAL,
		cv2.CHAIN_APPROX_SIMPLE)

	v = semantic_version.Version(cv2.__version__)
	if v.major == 3:
		image, contours, hierarchy = result
	else:
		contours, hierarchy = result

	contours = [fix_contour_pts(pts) for pts in contours]

	return [c for c in contours if c is not None]
コード例 #22
0
    def test_detecting_version(self):
        httpretty.register_uri(
            httpretty.POST,
            "http://example.com/api_jsonrpc.php",
            body=json.dumps({
                "jsonrpc": "2.0",
                "result": "4.0.0",
                "id": 0
            }),
        )

        zapi_detect = ZabbixAPI('http://example.com')
        self.assertEqual(zapi_detect.api_version(), '4.0.0')
        self.assertEqual(zapi_detect.version,
                         semantic_version.Version('4.0.0'))
コード例 #23
0
def test_update_with_metadata(isolated_pio_core, tmpdir_factory):
    storage_dir = tmpdir_factory.mktemp("storage")
    lm = LibraryPackageManager(str(storage_dir))

    # test non SemVer in registry
    pkg = lm.install("RadioHead @ <1.90", silent=True)
    outdated = lm.outdated(pkg)
    assert str(outdated.current) == "1.89.0"
    assert outdated.latest > semantic_version.Version("1.100.0")

    pkg = lm.install("ArduinoJson @ 5.10.1", silent=True)
    # tesy latest
    outdated = lm.outdated(pkg)
    assert str(outdated.current) == "5.10.1"
    assert outdated.wanted is None
    assert outdated.latest > outdated.current
    assert outdated.latest > semantic_version.Version("5.99.99")

    # test wanted
    outdated = lm.outdated(pkg, PackageSpec("ArduinoJson@~5"))
    assert str(outdated.current) == "5.10.1"
    assert str(outdated.wanted) == "5.13.4"
    assert outdated.latest > semantic_version.Version("6.16.0")

    # update to the wanted 5.x
    new_pkg = lm.update("ArduinoJson@^5",
                        PackageSpec("ArduinoJson@^5"),
                        silent=True)
    assert str(new_pkg.metadata.version) == "5.13.4"
    # check that old version is removed
    assert len(lm.get_installed()) == 2

    # update to the latest
    lm = LibraryPackageManager(str(storage_dir))
    pkg = lm.update("ArduinoJson", silent=True)
    assert pkg.metadata.version == outdated.latest
コード例 #24
0
ファイル: base.py プロジェクト: funn/django-systemjs
 def get_jspm_version(self, opts):
     jspm_bin = opts['jspm']
     cmd = '{} --version'.format(jspm_bin)
     proc = subprocess.Popen(cmd,
                             shell=True,
                             cwd=self.cwd,
                             stdout=self.stdout,
                             stdin=self.stdin,
                             stderr=self.stderr)
     result, err = proc.communicate()  # block until it's done
     if err:
         raise BundleError("Could not determine JSPM version, error: %s",
                           err)
     version_string = result.decode().split()[0]
     return semantic_version.Version(version_string, partial=True)
コード例 #25
0
def is_valid_proposed_version(release_context, proposed_version):
    validations = []
    sv = None
    if semantic_version.validate(proposed_version):
        sv = semantic_version.Version(proposed_version)
        if release_context.is_snapshot_release():
            validations.append(sv.prerelease
                               and sv.prerelease[0].upper() == SNAPSHOT)
        else:
            validations.append(not sv.prerelease)

    if all(v for v in validations):
        return sv
    else:
        None
コード例 #26
0
ファイル: version.py プロジェクト: U0001F3A2/golem
def update_ini():
    """
    Create a file ($GOLEM/.version.ini) with current Golem version
    """
    version_file = join(get_golem_path(), '.version.ini')
    version = semantic_version.Version(setup_commons.get_version())
    contents = ("[version]{sep}version = {version}{sep}"
                "number = {version_major}{sep}")
    contents = contents.format(
        sep=linesep,
        version=version,
        version_major=version.major,
    )
    with open(version_file, 'wb') as f_:
        f_.write(contents.encode('ascii'))
コード例 #27
0
 def verify_required_version(self):
     """Verify that the required version for the pod is met."""
     if self.pod.grow_version is None:
         return
     sem_current = semantic_version.Version(self.current_version)
     grow_version_pattern = '{}'.format(self.pod.grow_version)
     # Include pre-releases in the version check.
     if '-' not in grow_version_pattern:
         grow_version_pattern = '{}-'.format(grow_version_pattern)
     spec_required = semantic_version.SimpleSpec(grow_version_pattern)
     if sem_current not in spec_required:
         text = 'ERROR! Pod requires Grow SDK version: {}'.format(
             self.pod.grow_version)
         logging.error(colors.stylize(text, colors.ERROR))
         raise LatestVersionCheckError(text)
コード例 #28
0
def get_validator(rde_version: str) -> AbstractValidator:  # noqa: E501
    """Get the right instance of input validator.

    Factory method to return the Validator based on the RDE version in use.
    :param str rde_version: rde_version for which the corresponding validator
    needs to be returned.
    :rtype validator (container_service_extension.rde.validators.abstract_validator.AbstractValidator)  # noqa: E501
    """
    # Get the validator for the specified RDE version.
    rde_version: semantic_version.Version = semantic_version.Version(
        rde_version)  # noqa: E501
    if str(rde_version) == rde_constants.RDEVersion.RDE_1_0_0.value:
        return Validator_1_0_0()
    elif str(rde_version) == rde_constants.RDEVersion.RDE_2_0_0.value:
        return Validator_2_0_0()
コード例 #29
0
ファイル: servicemonitor.py プロジェクト: cmz0714/bk-bcs-saas
    def get(self, request, project_id, cluster_id):
        """获取targets列表
        """
        data = {"need_update": False, "update_tooltip": ""}

        # Mesos不存在Prometheus CRD, 直接返回
        if request.project.kind == ProjectKind.MESOS.value:
            return Response(data)

        access_token = request.user.token.access_token
        client = k8s.K8SClient(access_token, project_id, cluster_id, env=None)
        resp = client.get_prometheus("thanos",
                                     "po-prometheus-operator-prometheus")
        spec = resp.get("spec") or {}
        if not spec:
            raise error_codes.APIError(_("Prometheus未安装,请联系管理员解决"))

        for container in spec.get("containers") or []:
            if container["name"] not in settings.PROMETHEUS_VERSIONS:
                continue

            image = settings.PROMETHEUS_VERSIONS[container["name"]]
            if semantic_version.Version(
                    self._get_version(image)) <= semantic_version.Version(
                        self._get_version(container["image"])):
                continue

            update_tooltip = _(
                "当前【{}】版本较低, 查询 Endpoints 功能将不可用, 请升级到最新版本").format(
                    container["name"])
            need_update = True
            data["need_update"] = need_update
            data["update_tooltip"] = update_tooltip
            break

        return Response(data)
コード例 #30
0
ファイル: package.py プロジェクト: bitup-cs/IDE-config
    def max_satisfying_repo_version(versions, requirements=None):
        item = None
        systype = util.get_systype()
        reqspec = None
        if requirements:
            try:
                reqspec = semantic_version.Spec(requirements)
            except ValueError:
                pass

        for v in versions:
            if "system" in v and v['system'] not in ("all", "*") and \
                    systype not in v['system']:
                continue
            if "platformio" in v.get("engines", {}):
                if PkgRepoMixin.PIO_VERSION not in semantic_version.Spec(
                        v['engines']['platformio']):
                    continue
            specver = semantic_version.Version(v['version'])
            if reqspec and specver not in reqspec:
                continue
            if not item or semantic_version.Version(item['version']) < specver:
                item = v
        return item