Python semver.parse_version_info() Examples

The following are 14 code examples of semver.parse_version_info(). 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: test_cumulus_bootstrap.py    From aeon-ztps with Apache License 2.0 6 votes vote down vote up
def test_install_os_image_not_all_good(mock_exit_results, mock_os, mock_con, device, cli_args):
    image_name = 'test_image'
    errmsg = 'error running command'
    device.api.execute.return_value = (False, errmsg)
    local_cb = cumulus_bootstrap.CumulusBootstrap(args['server'], cli_args)
    local_cb.dev = device
    local_cb.image_name = image_name

    sem_ver = semver.parse_version_info(device.facts['os_version'])
    if sem_ver >= (3, 0, 0):
        # Cumulus 3.x install command
        cmd = 'sudo onie-select -rf'
    else:
        # Cumulus 2.x install command
        cmd = 'sudo /usr/cumulus/bin/cl-img-install -sf http://{server}/images/{os_name}/{image_name}'.format(
            server=local_cb.cli_args.server, os_name=_OS_NAME, image_name=image_name)

    with pytest.raises(SystemExit):
        local_cb.install_os()
    mock_exit_results.assert_called_with(results={'ok': False,
                                                  'error_type': 'install',
                                                  'message': 'Unable to run command: {cmd}. '
                                                             'Error message: {errmsg}'.format(cmd=cmd, errmsg=errmsg)}) 
Example #2
Source File: test_cumulus_bootstrap.py    From aeon-ztps with Apache License 2.0 6 votes vote down vote up
def test_install_os_image(mock_os, mock_con, mock_time, mock_wait_device,
                          mock_onie_install, mock_wait_for_onie, device, cli_args):
    image_name = 'test_image'
    results = 'test result message'
    device.api.execute.return_value = (True, results)
    local_cb = cumulus_bootstrap.CumulusBootstrap(args['server'], cli_args)
    local_cb.dev = device
    local_cb.image_name = image_name

    sem_ver = semver.parse_version_info(device.facts['os_version'])
    if sem_ver >= (3, 0, 0):
        # Cumulus 3.x install command
        cmd = 'sudo onie-select -rf'
        method_calls = [mock.call.execute([cmd]), mock.call.execute(['sudo reboot'])]
    else:
        # Cumulus 2.x install command
        cmd = 'sudo /usr/cumulus/bin/cl-img-install -sf http://{server}/images/{os_name}/{image_name}'.format(
            server=local_cb.cli_args.server, os_name=_OS_NAME, image_name=image_name)
        method_calls = [mock.call.execute([cmd])]

    local_cb.install_os()
    assert device.api.method_calls == method_calls 
Example #3
Source File: dag.py    From boundary-layer with Apache License 2.0 6 votes vote down vote up
def validate_compatibility_version(self, data):
        if not data.get('compatibility_version'):
            return

        version = None
        try:
            version = semver.parse_version_info(data['compatibility_version'])
        except ValueError:
            raise ValidationError('Must be a valid SemVer',
                                  ['compatibility_version'])

        if VERSION < version:
            raise ValidationError(
                'Incompatible boundary_layer version: This '
                'workflow requires boundary_layer version {} or higher! '
                'Current version is {}'.format(version, VERSION),
                ['compatibility_version'])

        if version < MIN_SUPPORTED_VERSION:
            raise ValidationError(
                'Incompatible boundary_layer version: This workflow '
                'is for the incompatible prior version {}. Use the '
                'migrate-workflow script to update it.'.format(version),
                ['compatibility_version']) 
Example #4
Source File: common.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_agent_tags(since, to):
    """
    Return a list of tags from integrations-core representing an Agent release,
    sorted by more recent first.
    """
    agent_tags = sorted(parse_version_info(t) for t in git_tag_list(r'^\d+\.\d+\.\d+$'))

    # default value for `to` is the latest tag
    if to:
        to = parse_version_info(to)
    else:
        to = agent_tags[-1]

    since = parse_version_info(since)

    # filter out versions according to the interval [since, to]
    agent_tags = [t for t in agent_tags if since <= t <= to]

    # reverse so we have descendant order
    return [str(t) for t in reversed(agent_tags)] 
Example #5
Source File: version_utils.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_version(raw_version):
    try:
        # Only works for MAJOR.MINOR.PATCH(-PRE_RELEASE)
        return semver.parse_version_info(raw_version)
    except ValueError:
        pass
    try:
        # Version may be missing minor eg: 10.0
        version = raw_version.split(' ')[0].split('.')
        version = [int(part) for part in version]
        while len(version) < 3:
            version.append(0)
        return semver.VersionInfo(*version)
    except ValueError:
        # Postgres might be in development, with format \d+[beta|rc]\d+
        match = re.match(r'(\d+)([a-zA-Z]+)(\d+)', raw_version)
        if match:
            version = list(match.groups())
            return semver.parse_version_info('{}.0.0-{}.{}'.format(*version))
    raise Exception("Cannot determine which version is {}".format(raw_version)) 
Example #6
Source File: test_meta.py    From reckoner with Apache License 2.0 5 votes vote down vote up
def test_version_is_valid(self):
        """Load the reckoner version and parse with semver"""
        assert semver.parse_version_info(reckoner_version) 
Example #7
Source File: terminal.py    From singularity-cli with Mozilla Public License 2.0 5 votes vote down vote up
def get_singularity_version_info():
    """get the full singularity client version as a semantic version"
    """
    version_string = get_singularity_version()
    prefix = "singularity version "
    if version_string.startswith(prefix):
        version_string = version_string[len(prefix) :]
    elif "/" in version_string:  # Handle old stuff like "x.y.z-pull/123-0a5d"
        version_string = version_string.replace("/", "+", 1)
    return semver.parse_version_info(version_string) 
Example #8
Source File: cumulus_bootstrap.py    From aeon-ztps with Apache License 2.0 5 votes vote down vote up
def ensure_os_version(self):
        self.check_os_install_and_finally()
        if not self.image_name:
            self.log.info('no software install required')
            return self.dev

        self.log.info('software image install required: %s' % self.image_name)
        self.install_os()

        self.log.info('software install OK')

        os_semver = semver.parse_version_info(self.dev.facts['os_version'])
        if os_semver.major < 3:
            self.log.info('rebooting device ... please be patient')

            self.post_device_status(message='OS install completed, now rebooting ... please be patient',
                                    state='OS-REBOOTING')

            self.dev.api.execute(['sudo reboot'])
            time.sleep(self.cli_args.init_delay)
            return self.wait_for_device(countdown=self.cli_args.reload_delay, poll_delay=10)


# ##### -----------------------------------------------------------------------
# #####
# #####                           !!! MAIN !!!
# #####
# ##### ----------------------------------------------------------------------- 
Example #9
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 #10
Source File: version.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def _parse_to_semver_and_metadata(version: str):
    def raise_invalid():
        raise ValueError(f'not a valid (semver) version: `{version}`')

    if not version:
        raise_invalid()

    semver_version = version
    metadata = _VersionMetadata()

    # strip leading `v`
    if version[0] == 'v':
        semver_version = version[1:]
        metadata.prefix = 'v'

    # in most cases, we should be fine now
    try:
        return semver.parse_version_info(semver_version), metadata
    except ValueError:
        pass # try extending `.0` as patch-level

    # blindly append patch-level
    if '-' in version:
        sep = '-'
    else:
        sep = '+'

    numeric, sep, suffix = semver_version.partition(sep)
    numeric += '.0'

    try:
        return semver.parse_version_info(numeric + sep + suffix), metadata
    except ValueError:
        # re-raise with original version str
        raise_invalid() 
Example #11
Source File: version_test.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def test_find_latest_version(self):
        versions = (semver.parse_version_info(v) for v in (
                '0.0.10',
                '0.20.1',
                '2.50.100',
                '3.0.1',
                '1.0.0',
        )
        )
        result = examinee.find_latest_version(versions)
        self.assertEqual(str(result), '3.0.1') 
Example #12
Source File: git.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_latest_tag(pattern=None, tag_prefix='v'):
    """
    Return the highest numbered tag (most recent)
    Filters on pattern first, otherwise based off all tags
    Removes prefixed `v` if applicable
    """
    if not pattern:
        pattern = rf'^({tag_prefix})?\d+\.\d+\.\d+.*'
    all_tags = sorted((parse_version_info(t.replace(tag_prefix, '', 1)), t) for t in git_tag_list(pattern))
    if not all_tags:
        return
    else:
        # reverse so we have descending order
        return list(reversed(all_tags))[0][1] 
Example #13
Source File: cloud_foundry_api.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def discover_api(self):
        # type: () -> Tuple[str, str]
        self.log.info("Discovering Cloud Foundry API version and authentication endpoint")
        try:
            res = self.http.get(self._api_url)
        except RequestException:
            self.log.exception("Error connecting to the API server")
            raise
        try:
            res.raise_for_status()
        except HTTPError:
            self.log.exception("Error querying API information: response: %s", res.text)
            raise
        try:
            payload = res.json()
        except ValueError:
            self.log.exception("Error decoding API information: response: %s", res.text)
            raise

        links = payload.get("links")
        if not links:
            raise CheckException("Unable to inspect API information from payload {}".format(payload))

        api_v3_version = "0.0.0"
        try:
            api_v3_version = links["cloud_controller_v3"]["meta"]["version"]
        except Exception:
            self.log.debug("cloud_controller_v3 information not found, defaulting to v2")

        try:
            uaa_url = links["uaa"]["href"]
        except Exception:
            raise CheckException("Unable to collect API version and/or UAA URL from links {}".format(links))

        api_version = "v2"
        if semver.parse_version_info(api_v3_version) >= MIN_V3_VERSION:
            api_version = "v3"
        self.log.info("Discovered API `%s` and UAA URL `%s`", api_version, uaa_url)
        return api_version, uaa_url 
Example #14
Source File: cumulus_bootstrap.py    From aeon-ztps with Apache License 2.0 4 votes vote down vote up
def install_os(self):
        vendor_dir = os.path.join(self.cli_args.topdir, 'vendor_images', self.os_name)

        image_fpath = os.path.join(vendor_dir, self.image_name)
        if not os.path.exists(image_fpath):
            errmsg = 'Image file does not exist: %s' % image_fpath
            self.log.error(errmsg)
            self.exit_results(results=dict(
                ok=False, error_type='install',
                message=errmsg))

        msg = 'Installing Cumulus image=[%s] ... this can take up to 30 min.' % self.image_name
        self.log.info(msg)
        self.post_device_status(message=msg, state='OS-INSTALL')

        os_semver = semver.parse_version_info(self.dev.facts['os_version'])

        # Cumulus 2.x upgrade command is removed in Cumulus 3.x, so two upgrade methods are required
        # Cumulus 2.x upgrade
        if os_semver.major == 2:
            install_command = 'sudo /usr/cumulus/bin/cl-img-install -sf http://{server}/images/{os_name}/{image_name}'.format(server=self.cli_args.server, os_name=self.os_name, image_name=self.image_name)
            all_good, results = self.dev.api.execute([install_command])
            if not all_good:
                errmsg = 'Unable to run command: {}. Error message: {}'.format(install_command, results)
                self.exit_results(results=dict(
                    ok=False,
                    error_type='install',
                    message=errmsg))
        # Cumulus 3.x upgrade
        else:
            install_command = 'sudo onie-select -rf'
            all_good, results = self.dev.api.execute([install_command])
            if not all_good:
                errmsg = 'Unable to run command: {}. Error message: {}'.format(install_command, results)
                self.exit_results(results=dict(
                    ok=False,
                    error_type='install',
                    message=errmsg))
            self.dev.api.execute(['sudo reboot'])
            time.sleep(60)

            # Boot into ONIE rescue mode
            self.wait_for_onie_rescue(countdown=300, poll_delay=10, user='root')

            # Download and verify OS
            self.onie_install()

            # Wait for onie-rescue shell to terminate
            time.sleep(60)

            # Wait for actual install to occur. This takes up to 30 min.
            self.wait_for_device(countdown=1800, poll_delay=30)