Python semver.match() Examples

The following are 21 code examples of semver.match(). 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: pkg_util.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def check_deps(dependencies, parent=""):
    if isinstance(dependencies, dict):
        for pkg_name, exp_ver in dependencies.items():
            if parent:
                full_name = "{} ({})".format(pkg_name, parent)
            else:
                full_name = pkg_name
            meta = getPackageMeta(pkg_name)
            ver = meta.__version__
            if MAJOR_MINOR_REGEX.fullmatch(ver):
                ver += ".0"  # Add a fictive patch number to fit semver format
            if not semver.match(ver, exp_ver):
                raise RuntimeError("Incompatible '{}' package version. "
                                   "Expected: {} "
                                   "Found: {}".
                                   format(pkg_name, exp_ver, ver))
            if hasattr(meta, "__dependencies__"):
                deps = meta.__dependencies__
                check_deps(deps, full_name)
    else:
        pkg = dependencies if isinstance(dependencies, str) else \
            dependencies.__name__
        meta = getPackageMeta(pkg)
        deps = meta.__dependencies__
        check_deps(deps) 
Example #2
Source File: __main__.py    From deosorg with GNU General Public License v3.0 6 votes vote down vote up
def main_create():
    """Main function for GPG identity creation."""
    p = argparse.ArgumentParser()
    p.add_argument('user_id')
    p.add_argument('-e', '--ecdsa-curve', default='nist256p1')
    p.add_argument('-t', '--time', type=int, default=int(time.time()))
    p.add_argument('-v', '--verbose', default=0, action='count')
    p.add_argument('-s', '--subkey', default=False, action='store_true')

    args = p.parse_args()
    util.setup_logging(verbosity=args.verbose)
    log.warning('This GPG tool is still in EXPERIMENTAL mode, '
                'so please note that the API and features may '
                'change without backwards compatibility!')

    existing_gpg = keyring.gpg_version().decode('ascii')
    required_gpg = '>=2.1.11'
    if semver.match(existing_gpg, required_gpg):
        run_create(args)
    else:
        log.error('Existing gpg2 has version "%s" (%s required)',
                  existing_gpg, required_gpg) 
Example #3
Source File: bootstrap.py    From ledger-api-py with Apache License 2.0 6 votes vote down vote up
def is_server_valid(server_list, network):
    # Check requested server is on list
    available_servers = [s['name'] for s in server_list]
    if network not in available_servers:
        raise NetworkUnavailableError('Requested network not present on network: {}'.format(network))

    # Check network version
    server_details = next(s for s in server_list if s['name'] == network)
    if server_details['versions'] != '*':
        version_constraints = server_details['versions'].split(',')

        # Build required version (e.g.: 0.9.1-alpha2 -> 0.9.0)
        network_version_required = _parse_python_version(__version__)
        network_version_required['prerelease'] = None
        network_version_required['build'] = None
        network_version_required['patch'] = 0
        network_version_required = semver.format_version(**network_version_required)

        if not all(semver.match(network_version_required, c) for c in version_constraints):
            raise IncompatibleLedgerVersion("Requested network does not support required version\n" +
                                            "Required version: {}\nNetwork supports: {}".format(
                                                network_version_required, ', '.join(version_constraints)
                                            ))
    # Return true if server valid
    return True 
Example #4
Source File: commands.py    From commandment with MIT License 5 votes vote down vote up
def for_platform(cls, platform: Platform, min_os_version: str, queries: Set[Queries] = None) -> 'DeviceInformation':
        """Generate a command that is compatible with the specified platform and OS version.

        Args:
              platform (Platform): Desired target platform
              min_os_version (str): Desired OS version
              queries (Set[Queries]): Desired Queries, or default to ALL queries.

        Returns:
              DeviceInformation instance with supported queries.
        """

        def supported(query) -> bool:
            if query not in cls.Requirements:
                return True

            platforms = cls.Requirements[query]
            for req_platform, req_min_version in platforms:
                if req_platform != platform:
                    continue

                # TODO: version checking
                return True  # semver only takes maj.min.patch
                #return semver.match(min_os_version, req_min_version)

            return False

        if queries is None:
            supported_queries = filter(supported, [q.value for q in cls.Queries])
        else:
            supported_queries = filter(supported, queries)

        return cls(Queries=list(supported_queries)) 
Example #5
Source File: semver.py    From repo2docker with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def match(self, v):
        """Check if `v` falls into the version range"""
        if self.exclusive:
            return self.lower <= v < self.upper
        else:
            return self.lower <= v <= self.upper 
Example #6
Source File: semver.py    From repo2docker with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def match(self, v):
        """Check if `v` matches the constraint"""
        while len(v) < 3:
            v = v + (0,)
        v_str = ".".join(map(str, v))
        return semver.match(v_str, self.constraint_str) 
Example #7
Source File: semver.py    From repo2docker with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_semver_match(constraint, versions_list):
    matcher = create_semver_matcher(constraint)
    for vstr in reversed(versions_list):
        if matcher.match(str_to_version(vstr)):
            return vstr
    return None 
Example #8
Source File: trezor.py    From deosorg with GNU General Public License v3.0 5 votes vote down vote up
def connect(self):
        """Enumerate and connect to the first USB HID interface."""
        def passphrase_handler(_):
            log.debug('using %s passphrase for %s',
                      'non-empty' if self.passphrase else 'empty', self)
            return self._defs.PassphraseAck(passphrase=self.passphrase)

        for d in self._defs.HidTransport.enumerate():
            log.debug('endpoint: %s', d)
            transport = self._defs.HidTransport(d)
            connection = self._defs.Client(transport)
            connection.callback_PassphraseRequest = passphrase_handler
            f = connection.features
            log.debug('connected to %s %s', self, f.device_id)
            log.debug('label    : %s', f.label)
            log.debug('vendor   : %s', f.vendor)
            current_version = '{}.{}.{}'.format(f.major_version,
                                                f.minor_version,
                                                f.patch_version)
            log.debug('version  : %s', current_version)
            log.debug('revision : %s', binascii.hexlify(f.revision))
            if not semver.match(current_version, self.required_version):
                fmt = ('Please upgrade your {} firmware to {} version'
                       ' (current: {})')
                raise ValueError(fmt.format(self, self.required_version,
                                            current_version))
            connection.ping(msg='', pin_protection=True)  # unlock PIN
            return connection
        raise interface.NotFoundError('{} not connected'.format(self)) 
Example #9
Source File: versioning.py    From st2 with Apache License 2.0 5 votes vote down vote up
def complex_semver_match(version, version_specifier):
    """
    Custom semver match function which also supports complex semver specifiers
    such as >=1.6, <2.0, etc.

    NOTE: This function also supports special "all" version specifier. When "all"
    is specified, any version provided will be considered valid.

    :rtype: ``bool``
    """
    if version_specifier == 'all':
        return True

    split_version_specifier = version_specifier.split(',')

    if len(split_version_specifier) == 1:
        # No comma, we can do a simple comparision
        return semver.match(version, version_specifier)
    else:
        # Compare part by part
        for version_specifier_part in split_version_specifier:
            version_specifier_part = version_specifier_part.strip()

            if not version_specifier_part:
                continue

            if not semver.match(version, version_specifier_part):
                return False

        return True 
Example #10
Source File: version.py    From st2 with Apache License 2.0 5 votes vote down vote up
def version_match(value, pattern):
    return semver.match(value, pattern) 
Example #11
Source File: loader.py    From rpmvenv with MIT License 5 votes vote down vote up
def validate_extensions(extensions):
    """Process the extension dependencies."""
    ext_map = dict(
        (ext.name, ext) for ext in extensions
    )

    for ext in extensions:

        for dependency, versions in ext.requirements.items():

            ext_dependency = ext_map.get(dependency, None)
            if not ext_dependency:

                raise MissingDependency(
                    '{0} is required by {1} but is not loaded.'.format(
                        ext.name,
                        dependency,
                    )
                )

            for version in versions:

                if not semver.match(ext.version, version):

                    raise InvalidDependency(
                        '{0}-{1} required by {2} but found {0}-{3}.'.format(
                            dependency,
                            version,
                            ext.name,
                            ext.version,
                        )
                    )

    return extensions 
Example #12
Source File: bootstrap.py    From ledger-api-py with Apache License 2.0 5 votes vote down vote up
def _parse_python_version(text):
    match = re.match(r'^(\d+)\.(\d+)\.\d+(?:[abd]\d+)?$', text.strip())
    if match is None:
        raise RuntimeError('Unable to parse python version')

    ver = {
        'major': int(match.group(1)),
        'minor': int(match.group(2)),
    }

    return ver 
Example #13
Source File: __init__.py    From ledger-api-py with Apache License 2.0 5 votes vote down vote up
def check_version_compatibility(reported_version, compatible_versions):
    server_version = _pre_process_version(reported_version)
    if server_version.startswith('Unknown version with hash'):
        logging.warning('Using development version')
    elif not all(semver.match(server_version, c) for c in compatible_versions):
        raise IncompatibleLedgerVersion("Ledger version running on server is not compatible with this API" +
                                        "\nServer version: {} \nExpected version: {}".format(
                                            server_version, ', '.join(compatible_versions))) 
Example #14
Source File: __init__.py    From ledger-api-py with Apache License 2.0 5 votes vote down vote up
def _pre_process_version(reported_version):
    server_version = reported_version.lstrip('v')

    # remove trailing git version if present
    match = re.match(r'^(\d+\.\d+\.\d+)-(alpha|beta|rc)(\d+)-\d+-(g[a-f0-9]+)$', str(server_version))
    if match is not None:
        server_version = '{}-{}.{}+{}'.format(match.group(1), match.group(2), match.group(3), match.group(4))

    match = re.match(r'^(\d+\.\d+\.\d+)-(alpha|beta|rc)(\d+)$', str(server_version))
    if match is not None:
        server_version = '{}-{}.{}'.format(match.group(1), match.group(2), match.group(3))

    return server_version 
Example #15
Source File: trezor.py    From trezor-agent with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _verify_version(self, connection):
        f = connection.features
        log.debug('connected to %s %s', self, f.device_id)
        log.debug('label    : %s', f.label)
        log.debug('vendor   : %s', f.vendor)
        current_version = '{}.{}.{}'.format(f.major_version,
                                            f.minor_version,
                                            f.patch_version)
        log.debug('version  : %s', current_version)
        log.debug('revision : %s', binascii.hexlify(f.revision))
        if not semver.match(current_version, self.required_version):
            fmt = ('Please upgrade your {} firmware to {} version'
                   ' (current: {})')
            raise ValueError(fmt.format(self, self.required_version,
                                        current_version)) 
Example #16
Source File: __init__.py    From trezor-agent with GNU Lesser General Public License v3.0 5 votes vote down vote up
def verify_gpg_version():
    """Make sure that the installed GnuPG is not too old."""
    existing_gpg = keyring.gpg_version().decode('ascii')
    required_gpg = '>=2.1.11'
    msg = 'Existing GnuPG has version "{}" ({} required)'.format(existing_gpg,
                                                                 required_gpg)
    if not semver.match(existing_gpg, required_gpg):
        log.error(msg) 
Example #17
Source File: repositories.py    From pyTenable with MIT License 4 votes vote down vote up
def device_info(self, id, dns=None, ip=None, uuid=None, fields=None):
        '''
        Retrieves the device information for the requested device on the
        associated repository.

        :sc-api:`repository: device info <Repository.html#RepositoryRESTReference-/repository/{id}/deviceInfo>`

        `repository: ip info <Repository.html#RepositoryRESTReference-/repository/{id}/ipInfo>`

        Args:
            id (int): The numeric id for the repository to query.
            dns (str): The DNS name to query
            fields (list, optional):
                The list of fields that are desired to be returned.  For details
                on what fields are available, please refer to the details on the
                request within the repository device info API doc.
            ip (str): The IP address to query
            uuid (str): The UUID to query.

        Returns:
            :obj:`dict`:
                The device resource.

        Examples:
            >>> host = sc.repositories.device_info(1, ip='192.168.0.1')
        '''
        # We will generally want to query the deviceInfo action, however if we
        # happen to be on a Tenable.sc instance version thats less than 5.7, we
        # have to instead query ipInfo.
        method = 'deviceInfo'
        if semver.match(self._api.version, '<5.7.0'):
            method = 'ipInfo'

        params = dict()
        if fields:
            params['fields'] = ','.join([self._check('field', f, str) for f in fields])
        if dns:
            params['dnsName'] = self._check('dns', dns, str)
        if ip:
            params['ip'] = self._check('ip', ip, str)
        if uuid:
            params['uuid'] = self._check('uuid', uuid, 'uuid')

        return self._api.get('repository/{}/{}'.format(
            self._check('id', id, int), method), params=params).json()['response'] 
Example #18
Source File: __init__.py    From pyTenable with MIT License 4 votes vote down vote up
def login(self, username=None, password=None,
              access_key=None, secret_key=None):
        '''
        Logs the user into Tenable.sc

        Args:
            username (str, optional): Username
            password (str, optional): Password
            access_key (str, optional): API Access Key
            secret_key (str, optional): API Secret Key

        Returns:
            None

        Examples:

            Using a username && password:

            >>> sc = TenableSC('127.0.0.1', port=8443)
            >>> sc.login('username', 'password')

            Using API Keys:

            >>> sc = TenableSC('127.0.0.1', port=8443)
            >>> sc.login(access_key='ACCESSKEY', secret_key='SECRETKEY')
        '''

        if username != None and password != None:
            resp = self.post('token', json={
                'username': username,
                'password': password
            })
            self._session.headers.update({
                'X-SecurityCenter': str(resp.json()['response']['token'])
            })

        elif access_key != None and secret_key != None:
            if semver.match(self.version, '<5.13.0'):
                raise ConnectionError(
                    'API Keys not supported on this version of Tenable.sc')
            self._session.headers.update({
                'X-APIKey': 'accessKey={}; secretKey={}'.format(
                    access_key, secret_key)
            })
            self._apikeys = True 
Example #19
Source File: git.py    From datmo with MIT License 4 votes vote down vote up
def __init__(self, filepath, execpath, remote_url=None):
        super(GitCodeDriver, self).__init__()
        self.filepath = filepath
        # Check if filepath exists
        if not os.path.exists(self.filepath):
            raise PathDoesNotExist(
                __("error", "controller.code.driver.git.__init__.dne",
                   filepath))
        self.execpath = execpath
        # Check the execpath and the version
        try:
            p = subprocess.Popen(
                [self.execpath, "version"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                cwd=self.filepath)
            out, err = p.communicate()
            out, err = out.decode(), err.decode()
            if err:
                raise GitExecutionError(
                    __("error", "controller.code.driver.git.__init__.giterror",
                       err))
            version = str(out.split()[2].split(".windows")[0])
            if not semver.match(version, ">=1.9.7"):
                raise GitExecutionError(
                    __("error",
                       "controller.code.driver.git.__init__.gitversion",
                       out.split()[2]))
        except Exception as e:
            raise GitExecutionError(
                __("error", "controller.code.driver.git.__init__.giterror",
                   str(e)))

        # TODO: handle multiple remote urls
        # self.git_host_driver = GitHostDriver()
        self.remote_url = remote_url

        self._is_initialized = self.is_initialized

        if self._is_initialized:
            # If initialized ensure .datmo is not in working tree else error
            if self.exists_datmo_files_in_worktree():
                raise DatmoFolderInWorkTree(
                    __("error", "controller.code.driver.git.__init__.datmo"))
            # If initialized ensure .datmo is ignored (in .git/info/exclude)
            self.ensure_datmo_files_ignored()
            # If initialized update remote information
            # if remote_url:
            #     self.remote("set-url", "origin", remote_url)
            # self._remote_url = self.remote_url
            # self._remote_access = False
        self.type = "git" 
Example #20
Source File: git.py    From datmo with MIT License 4 votes vote down vote up
def create_ref(self, commit_id=None):
        """Add remaining files, make a commit and add it to a datmo code ref

        Parameters
        ----------
        commit_id : str, optional
            if commit_id is given, it will not add files and not create a commit

        Returns
        -------
        commit_id : str
            commit id for the ref created

        Raises
        ------
        CommitDoesNotExist
            commit id specified does not match a valid commit within the tree
        CommitFailed
            commit could not be created
        """
        self.ensure_code_refs_dir()
        if not commit_id:
            try:
                _ = self.latest_commit()
                message = "auto commit by datmo"
            except Exception:
                message = "auto initial commit by datmo"
            # add files and commit changes on current branch
            self.add("-A")
            _ = self.commit(options=["-m", message])
            try:
                commit_id = self.latest_commit()
            except GitExecutionError as e:
                raise CommitFailed(
                    __("error",
                       "controller.code.driver.git.create_ref.cannot_commit",
                       str(e)))
        # writing git commit into ref if exists
        if not self.exists_commit(commit_id):
            raise CommitDoesNotExist(
                __("error", "controller.code.driver.git.create_ref.no_commit",
                   commit_id))
        # git refs for datmo for the latest commit id is created
        code_ref_path = os.path.join(self.filepath, ".git/refs/datmo/",
                                     commit_id)
        with open(code_ref_path, "wb") as f:
            f.write(to_bytes(commit_id))
        return commit_id 
Example #21
Source File: semver.py    From repo2docker with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def create_semver_matcher(constraint_str):
    """Create a matcher that can be used to match version tuples

    Version tuples are matched against the provided regex `constraint_str`.
    """
    constraint_str = constraint_str.strip()
    first_digit = re.search(r"\d", constraint_str)
    if not first_digit:
        # Invalid version string (no numbers in it)
        return ""
    constraint = str_to_version(constraint_str[first_digit.start() :])

    comparison_symbol = constraint_str[0 : first_digit.start()].strip()

    # Default to "^" search if no matching mode specified (up to next major version)
    if (first_digit.start() == 0) or (comparison_symbol == "^"):
        if major(constraint) == 0:
            # Also, julia treats pre-1.0 releases specially, as if the first
            # non-zero number is actually a major number:
            # https://docs.julialang.org/en/latest/stdlib/Pkg/#Caret-specifiers-1
            # So we need to handle it separately by bumping the first non-zero
            # enumber.
            for i, n in enumerate(constraint):
                if (
                    n != 0 or i == len(constraint) - 1
                ):  # (using the last existing number handles situations like "^0.0" or "^0")
                    upper = constraint[0:i] + (n + 1,)
                    break
            return VersionRange(constraint, upper, True)
        else:
            return VersionRange(constraint, (major(constraint) + 1,), True)

    # '~' matching (only allowed to bump the last present number by one)
    if comparison_symbol == "~":
        return VersionRange(
            constraint, constraint[:-1] + (constraint[-1] + 1,), exclusive=False
        )

    # Use semver package's comparisons for everything else:

    # semver requires three version numbers
    if len(constraint) < 3:
        while len(constraint) < 3:
            constraint = constraint + (0,)
        constraint_str = constraint_str[0 : first_digit.start()] + ".".join(
            map(str, constraint)
        )

    # Convert special comparison strings to format accepted by `semver` library.
    constraint_str = constraint_str.replace("≥", ">=").replace("≤", "<=")
    constraint_str = re.sub(r"(^|\b)=\b", "==", constraint_str)

    return SemverMatcher(constraint_str)