Python semver.compare() Examples

The following are 20 code examples of semver.compare(). 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 semver , or try the search function .
Example #1
Source File: helper.py    From terraform-compliance with MIT License 6 votes vote down vote up
def python_version_check():
    python_version = sys.version.split(' ')[0]

    if not python_version:
        raise TerraformComplianceInternalFailure('Could not determine python version. '
                                                 'Please post this to issues: '.format(sys.version))

    python_version = VersionInfo.parse(python_version)

    if compare(str(python_version), Defaults.supported_min_python_versions) < 0:
        console_write('ERROR: Python version {} is not supported. '
                      'You must have minimum {} version.'.format(python_version,
                                                                 Defaults.supported_min_python_versions[0]))
        sys.exit(1)


    return True 
Example #2
Source File: SnykReport.py    From reapsaw with Apache License 2.0 5 votes vote down vote up
def update_recommendations(vulnerabilities):
        recommendations = dict()
        for vuln in vulnerabilities:
            # dotnet issues don't have upgrades
            if not vuln['upgrades']:
                continue
            if vuln['from'][1] not in recommendations:
                recommendations[vuln['from'][1]] = vuln['upgrades'][1]
            else:

                module = vuln['upgrades'][1][:vuln['upgrades'][1].rfind('@')]
                if semver.compare(vuln['upgrades'][1].split('@')[-1], recommendations[vuln['from'][1]].split('@')[-1],
                                  loose=True) == -1:
                    max_version = recommendations[vuln['from'][1]].split('@')[-1]
                else:
                    max_version = vuln['upgrades'][1].split('@')[-1]
                recommendations[vuln['from'][1]] = '@'.join([module, max_version])
        for vuln in vulnerabilities:
            if vuln['language'] == 'dotnet':
                vuln['Recommendations'] = f'Upgrade `{vuln["top_level_module"]}` to the latest compatible version.'
                continue
            if semver.compare(vuln['from'][1].split("@")[-1], recommendations[vuln['from'][1]].split("@")[-1],
                              loose=True) == -1:
                vuln['Recommendations'] = (f'Upgrade `{vuln["top_level_module"]}` '
                                           f'to version {recommendations[vuln["from"][1]].split("@")[-1]} or higher')
            else:
                vuln['Recommendations'] = (f'Your dependencies are out of date. Please remove your `node_modules` '
                                           f'directory and lock file, run `npm install` and commit new lock file to '
                                           f'your repo. Note, this will likely make a lot of changes to lock file.') 
Example #3
Source File: versions.py    From raiden-contracts with MIT License 5 votes vote down vote up
def contracts_version_monitoring_service_takes_token_network_registry(
    version: Optional[str],
) -> bool:
    """ Returns true if the contracts_version's MonitoringService contracts

    expects a TokenNetworkRegistry address as a constructor argument.
    """
    if version is None:
        # stock version in `data`
        return True
    return compare(version, "0.22.0") > 0 
Example #4
Source File: versions.py    From raiden-contracts with MIT License 5 votes vote down vote up
def contracts_version_has_initial_service_deposit(version: Optional[str]) -> bool:
    if version is None:
        # contracts_versoin == None means the stock version in development.
        return True
    return compare(version, "0.18.0") > 0 
Example #5
Source File: versions.py    From raiden-contracts with MIT License 5 votes vote down vote up
def contracts_version_provides_services(version: Optional[str]) -> bool:
    if version is None:
        # contracts_version == None means the stock version in development.
        return True
    return compare(version, "0.8.0") >= 0 
Example #6
Source File: versions.py    From raiden-contracts with MIT License 5 votes vote down vote up
def contracts_version_with_max_token_networks(version: Optional[str]) -> bool:
    if version is None:
        # contracts_version == None means the stock version in development.
        return True
    return compare(version, "0.9.0") >= 0 
Example #7
Source File: testtools.py    From dvol with Apache License 2.0 5 votes vote down vote up
def _skip_max_docker_ver(ver):
    try:
        return compare(DOCKER_VERSION, ver) < 0
    except ValueError:
        return False 
Example #8
Source File: version.py    From st2 with Apache License 2.0 5 votes vote down vote up
def version_equal(value, pattern):
    return semver.compare(value, pattern) == 0 
Example #9
Source File: version.py    From st2 with Apache License 2.0 5 votes vote down vote up
def version_less_than(value, pattern):
    return semver.compare(value, pattern) == -1 
Example #10
Source File: version.py    From st2 with Apache License 2.0 5 votes vote down vote up
def version_more_than(value, pattern):
    return semver.compare(value, pattern) == 1 
Example #11
Source File: version.py    From st2 with Apache License 2.0 5 votes vote down vote up
def version_compare(value, pattern):
    return semver.compare(value, pattern) 
Example #12
Source File: course.py    From reckoner with Apache License 2.0 5 votes vote down vote up
def _compare_required_versions(self):
        """
        Compare installed versions of helm and reckoner to the minimum versions
        required by the course.yml
        Accepts no arguments
        """
        if self.minimum_versions is None:
            return True
        helm_minimum_version = self.minimum_versions.get('helm', '0.0.0')
        reckoner_minimum_version = self.minimum_versions.get('reckoner', '0.0.0')

        logging.debug("Helm Minimum Version is: {}".format(helm_minimum_version))
        logging.debug("Helm Installed Version is {}".format(self.helm.version))

        logging.debug("Reckoner Minimum Version is {}".format(reckoner_minimum_version))
        logging.debug("Reckoner Installed Version is {}".format(reckoner_version))

        r1 = semver.compare(reckoner_version, reckoner_minimum_version)
        if r1 < 0:
            raise MinimumVersionException("reckoner Minimum Version {} not met.".format(reckoner_minimum_version))

        r2 = semver.compare(self.helm.version, helm_minimum_version)
        if r2 < 0:
            raise MinimumVersionException("helm Minimum Version {} not met.".format(helm_minimum_version))

        return True 
Example #13
Source File: __init__.py    From pentagon with Apache License 2.0 5 votes vote down vote up
def migrate(branch='migration', yes=False):
    """ Find applicable migrations and run them """
    logging.info("Pentagon Version: {}".format(installed_version()))
    logging.info("Starting Repository Version: {}".format(current_version()))

    migrations = migrations_to_run(current_version(), available_migrations())
    if migrations:
        logging.info("There are Migrations to run: ")
        logging.info(migrations)
        if yes:
            for migration in migrations:
                logging.info('Starting migration: {}'.format(migration))
                migration_name = "migration_{}".format(migration.replace('.', '_'))
                migration_class = locate("pentagon.migration.migrations.{}".format(migration_name))
                migration_class.Migration(branch).start()
            logging.info("Migrations complete. Use git to merge the migration branch.")
            logging.info("Current Repository Version: {}".format(current_version()))
        else:
            logging.info("Use: `pentagon migrate --yes` to run migrations")
    else:
        logging.info("No Migrations to run.")
        compare_value = semver.compare(installed_version(), current_version())
        if compare_value == -1:
            logging.error("Repository Version > Installed Version. Upgrade Pentagon")
            sys.exit(1)
        elif compare_value == 1:
            logging.info("Installed Version > Repository Version.")
            logging.info(" Use `pentagon migrate --yes` to update Repository Version")
            if yes:
                Migration(None).version_only()
        elif compare_value == 0:
            logging.info("You are at the latest version!") 
Example #14
Source File: test_cumulus_bootstrap.py    From aeon-ztps with Apache License 2.0 5 votes vote down vote up
def test_ensure_os_version(mock_wait_for_device, mock_get_os, mock_install_os, mock_time, device, cli_args):
    results = 'test result message'
    device.api.execute.return_value = (True, results)
    ver_required = '3.1.2'
    device_semver = semver.parse_version_info(device.facts['os_version'])
    image_name = 'image_file_name'

    def mock_get_os_function():
        diff = semver.compare(device.facts['os_version'], ver_required)
        # Check if upgrade is required
        if diff < 0:
            # upgrade required
            local_cb.image_name = image_name
        else:
            # upgrade not required
            local_cb.image_name = None
    mock_get_os.side_effect = mock_get_os_function
    local_cb = cumulus_bootstrap.CumulusBootstrap(args['server'], cli_args)
    local_cb.dev = device
    local_cb.ensure_os_version()

    # If upgrade was required, check that the correct calls were made
    if local_cb.image_name:
        assert mock_install_os.called_with(mock.call(device), image_name=image_name)
        if device_semver < (3, 0, 0):
            device.api.execute.assert_called_with(['sudo reboot'])
            mock_wait_for_device.assert_called_with(countdown=local_cb.cli_args.reload_delay, poll_delay=10)
        else:
            # Ensure device was not rebooted if v3 or greater, and wait_for_device was called
            assert not device.api.execute.called
    else:
        assert not device.api.execute.called
        assert not mock_install_os.called 
Example #15
Source File: pr_from_new_release.py    From mattermost-openshift with GNU General Public License v3.0 5 votes vote down vote up
def main():
    """lets start our task"""
    # clone the repo
    cleanup(LOCAL_WORK_COPY)
    try:
        r = Repo.clone_from(git_url, LOCAL_WORK_COPY)
    except GitCommandError as git_error:
        print(git_error)
        exit(-1)

    d = feedparser.parse(
        'https://github.com/mattermost/mattermost-server/releases.atom')
    release_version = d.entries[0].title[1:]

    # lets read the dockerfile of the current master
    dfp = DockerfileParser()

    with open('./mattermost-openshift-workdir/Dockerfile') as f:
        dfp.content = f.read()

    if 'MATTERMOST_VERSION' in dfp.envs:
        dockerfile_version = dfp.envs['MATTERMOST_VERSION']

    # Lets check if we got a new release
    if semver.compare(release_version, dockerfile_version) == 1:
        print("Updating from %s to %s" % (dockerfile_version, release_version))

        target_branch = 'bots-life/update-to-' + release_version

        if not pr_in_progress(target_branch):
            patch_and_push(dfp, r, target_branch, release_version)
            cleanup(LOCAL_WORK_COPY)

            create_pr_to_master(target_branch)
        else:
            print("There is an open PR for %s, aborting..." %
                  (target_branch))

    else:
        print("we are even with Mattermost %s, no need to update" %
              release_version) 
Example #16
Source File: course.py    From autohelm with Apache License 2.0 5 votes vote down vote up
def _compare_required_versions(self):
        """
        Compare installed versions of helm and autohelm to the minimum versions
        required by the course.yml
        Accepts no arguments
        """
        if self.minimum_versions is None:
            return True
        helm_minimum_version = self.minimum_versions.get('helm', '0.0.0')
        autohelm_minimum_version = self.minimum_versions.get('autohelm', '0.0.0')

        logging.debug("Helm Minimum Version is: {}".format(helm_minimum_version))
        logging.debug("Helm Installed Version is {}".format(self.helm.client_version))

        logging.debug("Autohelm Minimum Version is {}".format(autohelm_minimum_version))
        logging.debug("Autohelm Installed Version is {}".format(autohelm_version))

        r1 = semver.compare(autohelm_version, autohelm_minimum_version)
        if r1 < 0:
            raise MinimumVersionException("autohelm Minimum Version {} not met.".format(autohelm_minimum_version))

        if not self.config.local_development:
            r2 = semver.compare(self.helm.client_version, helm_minimum_version)
            if r2 < 0:
                raise MinimumVersionException("helm Minimum Version {} not met.".format(helm_minimum_version))

        return True 
Example #17
Source File: device.py    From balena-sdk-python with Apache License 2.0 5 votes vote down vote up
def __check_local_mode_supported(self, device):
        if not self.__is_provisioned_device(device):
            raise exceptions.LocalModeError(Message.DEVICE_NOT_PROVISIONED)

        if semver.compare(self.device_os._DeviceOs__normalize_balena_semver(device['os_version']), LOCAL_MODE_MIN_OS_VERSION) < 0:
            raise exceptions.LocalModeError(Message.DEVICE_OS_NOT_SUPPORT_LOCAL_MODE)

        if semver.compare(self.device_os._DeviceOs__normalize_balena_semver(device['supervisor_version']), LOCAL_MODE_MIN_SUPERVISOR_VERSION) < 0:
            raise exceptions.LocalModeError(Message.DEVICE_SUPERVISOR_NOT_SUPPORT_LOCAL_MODE)

        if device['os_variant'] != 'dev':
            raise exceptions.LocalModeError(Message.DEVICE_OS_TYPE_NOT_SUPPORT_LOCAL_MODE) 
Example #18
Source File: hup.py    From balena-sdk-python with Apache License 2.0 5 votes vote down vote up
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']) 
Example #19
Source File: deprecation_checker.py    From k8s-handle with Apache License 2.0 5 votes vote down vote up
def _is_server_version_greater(self, checked_version):
        return True if semver.compare(self.server_version, checked_version) >= 0 else False 
Example #20
Source File: device.py    From balena-sdk-python with Apache License 2.0 4 votes vote down vote up
def start_os_update(self, uuid, target_os_version):
        """
        Start an OS update on a device.

        Args:
            uuid (str): device uuid.
            target_os_version (str): semver-compatible version for the target device.
                Unsupported (unpublished) version will result in rejection.
                The version **must** be the exact version number, a "prod" variant and greater than the one running on the device.

        Returns:
            dict: action response.

        Raises:
            DeviceNotFound: if device couldn't be found.
            InvalidParameter|OsUpdateError: if target_os_version is invalid.

        Examples:
            >>> balena.models.device.start_os_update('b6070f4fea5edf808b576123157fe5ec', '2.29.2+rev1.prod')
            {u'status': u'in_progress', u'action': u'resinhup', u'parameters': {u'target_version': u'2.29.2+rev1.prod'}, u'last_run': 1554490809219L}
        """

        raw_query = "$filter=uuid%20eq%20'{uuid}'&$expand=is_of__device_type($select=slug)".format(uuid=uuid)

        device = self.base_request.request(
            'device', 'GET', raw_query=raw_query,
            endpoint=self.settings.get('pine_endpoint')
        )['d']

        if not device:
            raise exceptions.DeviceNotFound(uuid)
        device = device[0]

        # this will throw an error if the action is not available
        self.__check_os_update_target(device, target_os_version)

        all_versions = self.device_os.get_supported_versions(device['is_of__device_type'][0]['slug'])['versions']
        if not [v for v in all_versions if semver.compare(target_os_version, v) == 0]:
            raise exceptions.InvalidParameter('target_os_version', target_os_version)

        data = {
            'parameters': {
                'target_version': target_os_version
            }
        }

        return self.base_request.request(
            '{uuid}/{action_name}'.format(uuid=uuid, action_name=self.device_os.OS_UPDATE_ACTION_NAME),
            'POST',
            data=data,
            endpoint='https://actions.{device_url_base}/{device_actions_api_version}/'.format(
                device_url_base=self.config.get_all()['deviceUrlsBase'],
                device_actions_api_version=self.settings.get('device_actions_endpoint_version')
            )
        )