当前位置: 首页>>代码示例>>Python>>正文


Python semver.parse方法代码示例

本文整理汇总了Python中semver.parse方法的典型用法代码示例。如果您正苦于以下问题:Python semver.parse方法的具体用法?Python semver.parse怎么用?Python semver.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在semver的用法示例。


在下文中一共展示了semver.parse方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: bump

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def bump(segment=None, version_file=None):
    import semver
    if not version_file:
        version_file = get_version_file_path()
    try:
        with open(version_file) as version:
            version_text = version.read().strip()
        _ = semver.parse(version_text)
    except FileNotFoundError:
        LOGGER.error('Could not find .VERSION file')
        raise SystemExit(1)
    except ValueError:
        LOGGER.error('Invalid version found in .VERSION file "%s"', version_text)
        raise SystemExit(1)
    if segment:
        if segment not in ('major', 'minor', 'patch'):
            LOGGER.error('Invalid segment "%s" was provided for semantic versioning, exiting...')
            raise SystemExit(1)
        new_version = getattr(semver, f'bump_{segment}')(version_text)
        with open(version_file, 'w') as vfile:
            vfile.write(new_version)
            return new_version
    else:
        return version_text 
开发者ID:costastf,项目名称:toonapilib,代码行数:26,代码来源:core_library.py

示例2: versioning

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def versioning(version: str) -> str:
    """
    version to specification
    Author: Huan <zixia@zixia.net> (https://github.com/huan)

    X.Y.Z -> X.Y.devZ

    """
    sem_ver = semver.parse(version)

    major = sem_ver['major']
    minor = sem_ver['minor']
    patch = str(sem_ver['patch'])

    if minor % 2:
        patch = 'dev' + patch

    fin_ver = '%d.%d.%s' % (
        major,
        minor,
        patch,
    )

    return fin_ver 
开发者ID:wechaty,项目名称:python-wechaty,代码行数:26,代码来源:setup.py

示例3: from_str

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def from_str(cls, version_str):
        """ Parse version information from a string. """
        matches = Semver.SEMVER_RE.match(version_str)
        if matches:
            args = list(matches.groups())
            if not matches.group(3):
                args.append('0')
            return Semver(*map(int, filter(partial(is_not, None), args)))

        parts = parse(version_str)

        return cls(
            parts['major'],
            parts['minor'],
            parts['patch'],
            parts['prerelease'],
            parts['build']
        ) 
开发者ID:hyperledger,项目名称:aries-staticagent-python,代码行数:20,代码来源:type.py

示例4: get_hup_action_type

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def get_hup_action_type(self, device_type, current_version, target_version):
        """
        getHUPActionType in Python
        ref: https://github.com/balena-io-modules/balena-hup-action-utils/blob/master/lib/index.ts#L67
        """

        try:
            parsed_current_ver = semver.parse(current_version)
        except:
            raise exceptions.OsUpdateError('Invalid current balenaOS version')

        try:
            parsed_target_ver = semver.parse(target_version)
        except:
            raise exceptions.OsUpdateError('Invalid target balenaOS version')

        if parsed_current_ver['prerelease'] or parsed_target_ver['prerelease']:
            raise exceptions.OsUpdateError('Updates cannot be performed on pre-release balenaOS versions')

        xstr = lambda s: '' if s is None else str(s)
        if 'dev' in xstr(parsed_current_ver['prerelease']) + xstr(parsed_target_ver['prerelease']) + xstr(parsed_target_ver['build']) + xstr(parsed_current_ver['build']):
            raise exceptions.OsUpdateError('Updates cannot be performed on development balenaOS variants')

        if semver.compare(target_version, current_version) < 0:
            raise exceptions.OsUpdateError('OS downgrades are not allowed')

        # For 1.x -> 2.x or 2.x to 2.x only
        if parsed_target_ver['major'] > 1 and semver.compare(target_version, self.MIN_TARGET_VERSION) < 0:
            raise exceptions.OsUpdateError('Target balenaOS version must be greater than {0}'.format(self.MIN_TARGET_VERSION))

        return 'resinhup{from_v}{to_v}'.format(from_v=parsed_current_ver['major'], to_v=parsed_target_ver['major']) 
开发者ID:balena-io,项目名称:balena-sdk-python,代码行数:33,代码来源:hup.py

示例5: get_device_os_semver_with_variant

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def get_device_os_semver_with_variant(self, os_version, os_variant=None):
        """
        Get current device os semver with variant.

        Args:
            os_version (str): current os version.
            os_variant (Optional[str]): os variant.

        Examples:
            >>> balena.models.device_os.get_device_os_semver_with_variant('balenaOS 2.29.2+rev1', 'prod')
            '2.29.2+rev1.prod'

        """

        if not os_version:
            return None

        version_info = semver.VersionInfo.parse(self.__normalize_balena_semver(os_version))

        if not version_info:
            return os_version

        tmp = []
        if version_info.prerelease:
            tmp = version_info.prerelease.split('.')
        if version_info.build:
            tmp = tmp + version_info.build.split('.')

        xstr = lambda s: '' if s is None else str(s)
        return semver.format_version(
            version_info.major,
            version_info.minor,
            version_info.patch,
            version_info.prerelease,
            xstr(version_info.build) + '.' + os_variant if os_variant and os_variant not in tmp else version_info.build
        ) 
开发者ID:balena-io,项目名称:balena-sdk-python,代码行数:38,代码来源:device_os.py

示例6: get_supported_versions

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def get_supported_versions(self, device_type):
        """
        Get OS supported versions.

        Args:
            device_type (str): device type slug

        Returns:
            dict: the versions information, of the following structure:
                * versions - an array of strings, containing exact version numbers supported by the current environment.
                * recommended - the recommended version, i.e. the most recent version that is _not_ pre-release, can be `None`.
                * latest - the most recent version, including pre-releases.
                * default - recommended (if available) or latest otherwise.

        """

        response = self.base_request.request(
            '/device-types/v1/{device_type}/images'.format(device_type=device_type), 'GET',
            endpoint=self.settings.get('api_endpoint'), auth=False
        )

        potential_recommended_versions = [i for i in response['versions'] if not re.search(r'(\.|\+|-)dev', i)]
        potential_recommended_versions = [i for i in potential_recommended_versions if not semver.parse(i)['prerelease']]
        recommended = potential_recommended_versions[0] if potential_recommended_versions else None

        return {
            'versions': response['versions'],
            'recommended': recommended,
            'latest': response['latest'],
            'default': recommended if recommended else response['latest']
        } 
开发者ID:balena-io,项目名称:balena-sdk-python,代码行数:33,代码来源:device_os.py

示例7: get_job_version_array

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def get_job_version_array(self, version):
        """Gets the Job version either from field or manifest as an array of integers
        for sorting using the semver package. The result will be an array of length
        4 with the first three being integers containing major,minor and patch version
        numbers. The fourth will be either a None value or if a prerelease value is
        present this function will attempt to convert it into an integer for sorting.

        :keyword version: The version of the job type
        :type version: :class:`django.db.models.CharField`
        :return: the version array
        :rtype: array
        """

        parts = None
        try:
            parts = semver.parse(version)
        except:
            return [0,0,0,0]
        prerelease = None
        if parts['prerelease']:
            # attempt to convert pre-release field to a number for sorting
            # we want a non-null value if there is a pre-release field in version as
            # null values come first when sorting by descending order so we want
            # any prerelease versions to have a non-null value
            prerelease = re.sub("[^0-9]", "", parts['prerelease'])
            try:
                prerelease = int(prerelease)
            except ValueError:
                prerelease = ord(parts['prerelease'][0])
        version_array = [parts['major'], parts['minor'], parts['patch'], prerelease]

        return version_array 
开发者ID:ngageoint,项目名称:scale,代码行数:34,代码来源:models.py

示例8: version_strip_patch

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def version_strip_patch(value):
    return "{major}.{minor}".format(**semver.parse(value)) 
开发者ID:StackStorm,项目名称:st2,代码行数:4,代码来源:version.py

示例9: download

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def download(self, raw=False, **data):
        """
        Download an OS image. This function only works if you log in using credentials or Auth Token.

        Args:
            raw (bool): determining function return value.
            **data: os parameters keyword arguments.
                version (str): the balenaOS version of the image. The SDK will try to parse version into semver-compatible version, unsupported (unpublished) version will result in rejection.
                appId (str): the application ID.
                network (str): the network type that the device will use, one of 'ethernet' or 'wifi'.
                fileType (Optional[str]): one of '.img' or '.zip' or '.gz', defaults to '.img'.
                wifiKey (Optional[str]): the key for the wifi network the device will connect to if network is wifi.
                wifiSsid (Optional[str]): the ssid for the wifi network the device will connect to if network is wifi.
                appUpdatePollInterval (Optional[str]): how often the OS checks for updates, in minutes.

        Returns:
            object:
                If raw is True, urllib3.HTTPResponse object is returned.
                If raw is False, original response object is returned.

        Notes:
            default OS image file name can be found in response headers.

        Examples:
            >>> data = {'appId': '1476418', 'network': 'ethernet', 'version': '2.43.0+rev1.prod'}
            >>> response = balena.models.device_os.download(**data)
            >>> type(response)
            <class 'requests.models.Response'>
            >>> response['headers']
            >>> response.headers
            {'Content-Length': '134445838', 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Application-Record-Count, MaxDataServiceVersion, X-Requested-With, X-Balena-Client', 'content-disposition': 'attachment; filename="balena-cloud-FooBar4-raspberry-pi2-2.43.0+rev1-v10.2.2.img.zip"', 'X-Content-Type-Options': 'nosniff', 'Access-Control-Max-Age': '86400', 'x-powered-by': 'Express', 'Vary': 'X-HTTP-Method-Override', 'x-transfer-length': '134445838', 'Connection': 'keep-alive', 'Access-Control-Allow-Credentials': 'true', 'Date': 'Tue, 07 Jan 2020 17:40:52 GMT', 'X-Frame-Options': 'DENY', 'Access-Control-Allow-Methods': 'GET, PUT, POST, PATCH, DELETE, OPTIONS, HEAD', 'Content-Type': 'application/zip', 'Access-Control-Allow-Origin': '*'}

        """

        self.params = self.parse_params(**data)
        data['version'] = self.get_device_os_semver_with_variant(data['version'])

        response = self.base_request.request(
            'download', 'POST', data=data,
            endpoint=self.settings.get('api_endpoint'), stream=True, login=True
        )
        if raw:
            # return urllib3.HTTPResponse object
            return response.raw
        else:
            return response 
开发者ID:balena-io,项目名称:balena-sdk-python,代码行数:48,代码来源:device_os.py

示例10: download_unconfigured_image

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def download_unconfigured_image(self, device_type, version, raw=False):
        """
        Download an unconfigured OS image.

        Args:
            device_type (str): device type slug.
            version (str): the balenaOS version of the image. The SDK will try to parse version into semver-compatible version, unsupported (unpublished) version will result in rejection.
            raw (bool): determining function return value.

        Returns:
            object:
                If raw is True, urllib3.HTTPResponse object is returned.
                If raw is False, original response object is returned.

        Notes:
            default OS image file name can be found in response headers.

        Examples:
            >>> response = balena.models.device_os.download_unconfigured_image('raspberry-pi2', 'latest')
            >>> type(response)
            <class 'requests.models.Response'>
            >>> response['headers']
            >>> response.headers
            {'Access-Control-Allow-Headers': 'Content-Type, Authorization, Application-Record-Count, MaxDataServiceVersion, X-Requested-With, X-Balena-Client', 'content-disposition': 'attachment; filename="balena-cloud-raspberry-pi2-2.43.0+rev1-v10.2.2.img"', 'X-Content-Type-Options': 'nosniff', 'Access-Control-Max-Age': '86400', 'Transfer-Encoding': 'chunked', 'x-powered-by': 'Express', 'content-encoding': 'gzip', 'x-transfer-length': '134445269', 'last-modified': 'Mon, 23 Sep 2019 15:21:33 GMT', 'Connection': 'keep-alive', 'Access-Control-Allow-Credentials': 'true', 'Date': 'Tue, 07 Jan 2020 18:14:47 GMT', 'X-Frame-Options': 'DENY', 'Access-Control-Allow-Methods': 'GET, PUT, POST, PATCH, DELETE, OPTIONS, HEAD', 'Content-Type': 'application/octet-stream', 'Access-Control-Allow-Origin': '*'}

        """

        if version == 'latest':
            version = self.get_supported_versions(device_type)['latest']
        else:
            version = self.get_device_os_semver_with_variant(version)

        response = self.base_request.request(
            '/download?deviceType={device_type}&version={version}'.format(device_type=device_type, version=version),
            'GET',
            endpoint=self.settings.get('api_endpoint'), stream=True, auth=False
        )
        if raw:
            # return urllib3.HTTPResponse object
            return response.raw
        else:
            return response 
开发者ID:balena-io,项目名称:balena-sdk-python,代码行数:44,代码来源:device_os.py

示例11: get_log_json

# 需要导入模块: import semver [as 别名]
# 或者: from semver import parse [as 别名]
def get_log_json(self, include_stdout=True, include_stderr=True, since=None):
        """Get log data from elasticsearch as a dict (from the raw JSON).

        :param include_stdout: If True, include stdout in the result
        :type include_stdout: bool
        :param include_stderr: If True include stderr in the result
        :type include_stderr: bool
        :param since: If present, only retrieve logs since this timestamp (non-inclusive).
        :type since: :class:`datetime.datetime` or None
        :rtype: tuple of (dict, :class:`datetime.datetime`) with the results or None and the last modified timestamp
        """

        # If job_exe has not started
        if not self.started:
            return None, timezone.now()

        if settings.ELASTICSEARCH_VERSION and settings.ELASTICSEARCH_VERSION.startswith('2.'):
            extension = ".raw"
        else:
            extension = ".keyword"

        q = {
                'size': 10000,
                'query': {
                    'bool': {
                        'must': [
                            {'term': {'scale_job_exe'+extension: self.get_cluster_id()}}
                        ]
                    }
                },
                'sort': [{'@timestamp': 'asc'}, {'scale_order_num': 'asc'}],
                '_source': ['@timestamp', 'scale_order_num', 'message', 'stream', 'scale_job_exe']
            }
        if not include_stdout and not include_stderr:
            return None, timezone.now()
        elif include_stdout and not include_stderr:
            q['query']['bool']['must'].append({'term': {'stream'+extension: 'stdout'}})
        elif include_stderr and not include_stdout:
            q['query']['bool']['must'].append({'term': {'stream'+extension: 'stderr'}})
        if since is not None:
            q['query']['bool']['must'].append({'range': {'@timestamp': {'gte': since.isoformat()}}})

        hits = settings.ELASTICSEARCH.search(index='logstash-*,scalelogs-*', body=q)

        if hits['hits']['total'] == 0:
            return None, timezone.now()
        last_modified = max([util.parse.parse_datetime(h['_source']['@timestamp']) for h in hits['hits']['hits']])
        return hits, last_modified 
开发者ID:ngageoint,项目名称:scale,代码行数:50,代码来源:models.py


注:本文中的semver.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。