def getspecs(self, inputversion): inputversion = inputversion.strip() specarray = [] if inputversion.startswith("http"): pass elif inputversion.startswith("file"): pass elif inputversion.startswith("latest"): pass elif "||" in inputversion: inverarr = inputversion.split("||") for inver in inverarr: inver = inver.strip() if " " in inver: inver = inver.replace(" ", ",") s = Spec(inver) specarray.append(s) else: s = Spec(inver) specarray.append(s) elif "-" in inputversion: pass elif inputversion.endswith(".x"): inputversion = inputversion.replace(".x", ".0") inputversion = ">=" + inputversion s = Spec(inputversion) specarray.append(s) elif " " in inputversion: inputversion = inputversion.replace(" ", ",") s = Spec(inputversion) specarray.append(s) else: s = Spec(inputversion) specarray.append(s) return specarray
def get_npm_latest_version(output, range): versions = map(str, output['versions'].keys()) versions = map(Version, versions) range_spec = Spec(range) versions = range_spec.filter(versions) for v in versions: version = v return str(version)
def select_version(versions_str, query, stable=False): if isinstance(query, str): query = query.split(",") query = [x.replace(" ", "") for x in query] stable = True if "-" in str(query): stable = False spec = Spec(*query) return spec.select(versions(versions_str, stable))
def check_arcli_version(cls, arcli): current_version = pkg_resources.get_distribution('arcli').version required_version = Spec(arcli) if not required_version.match(Version(current_version)): raise InvalidArcliFileContents( 'Invalid Arcli version for this project. ' '(Installed {}, Required {})'.format(current_version, required_version)) return current_version
def split_namespec(namespec): find_mark = _VERSION_SPECIFIER_RE.search(namespec) if find_mark is None: name = namespec spec = Spec() else: name = namespec[:find_mark.start()] spec = Spec(namespec[find_mark.start():]) return name, spec
def version_match(app, given_versions, way): app_versions = given_versions[app.name] if app.name in given_versions else [] if validate(app.version): matching_versions = [] s = Spec("%s%s" % (way, app.version)) for version in app_versions: if s.match(Version(version)): matching_versions.append(version) return matching_versions return app_versions
def main(): vs = [ "0.2.0", "0.1.6", "0.1.5", "0.1.4", "0.1.3", "0.1.2", "0.1.1", "0.1.0" ] s = Spec('>=0.1.3,<0.2.0') print('versions:', vs) print('rule:', s.specs, '\n') versions = [Version(v) for v in vs] filtered = [str(v) for v in s.filter(versions)] print('filtered:', filtered) print('selected:', s.select(versions))
def _select_pragma_version(pragma_string, version_list): comparator_set_range = pragma_string.replace(" ", "").split('||') comparator_regex = re.compile(r"(([<>]?=?|\^)\d+\.\d+\.\d+)+") version = None for comparator_set in comparator_set_range: spec = Spec(*(i[0] for i in comparator_regex.findall(comparator_set))) selected = spec.select(version_list) if selected and (not version or version < selected): version = selected if version: return str(version)
def get_solc_backend_class_for_version(solc_version): if is_string(solc_version): solc_version = Version(solc_version) if solc_version in Spec('<=0.4.8'): return SolcCombinedJSONBackend elif solc_version in Spec('>=0.4.11'): return SolcStandardJSONBackend else: raise OSError( "The installed solc compiler is not supported. Supported versions " "of the solc compiler are <=0.4.8 and >=0.4.11")
def find_version_by_spec(self, artifact): path = "/%s/%s" % (artifact.path(False), self.metadata_file_name) content = self._getContent( self.base + path, "Failed to retrieve the maven metadata file: " + path) xml = etree.fromstring(content) original_versions = xml.xpath( "/metadata/versioning/versions/version/text()") versions = [] for version in original_versions: try: versions.append(Version.coerce(version)) except ValueError: # This means that version string is not a valid semantic versioning pass parse_versions_syntax = { # example -> (,1.0] r"^\(,(?P<upper_bound>[0-9.]*)]$": "<={upper_bound}", # example -> 1.0 r"^(?P<version>[0-9.]*)$": "~={version}", # example -> [1.0] r"^\[(?P<version>[0-9.]*)\]$": "=={version}", # example -> [1.2, 1.3] r"^\[(?P<lower_bound>[0-9.]*),\s*(?P<upper_bound>[0-9.]*)\]$": ">={lower_bound},<={upper_bound}", # example -> [1.2, 1.3) r"^\[(?P<lower_bound>[0-9.]*),\s*(?P<upper_bound>[0-9.]+)\)$": ">={lower_bound},<{upper_bound}", # example -> [1.5,) r"^\[(?P<lower_bound>[0-9.]*),\)$": ">={lower_bound}", } for regex, spec_format in parse_versions_syntax.items(): regex_result = match(regex, artifact.version_by_spec) if regex_result: spec = Spec(spec_format.format(**regex_result.groupdict())) selected_version = spec.select(versions) if not selected_version: raise ValueError( "No version found with this spec version: {0}".format( artifact.version_by_spec)) # To deal when repos on maven don't have patch number on first build (e.g. 3.8 instead of 3.8.0) if str(selected_version) not in original_versions: selected_version.patch = None return str(selected_version) raise ValueError("The spec version {0} is not supported! ".format( artifact.version_by_spec))
class PackageRequirement(object): def __init__(self, name, spec): self.name = name self.spec_string = spec self.spec = Spec(spec) self.required_by = [] def match(self, version): return self.spec.match(version.version) def filter(self, versions): return filter(lambda v: self.spec.match(v.version), versions) def __repr__(self): return '"%s" %s' % (self.name, self.spec)
def get_spec(candidates, name): specs = [] for package in candidates: deps = package.get_dependency_configurations() for d_name, spec in deps: if name == d_name: specs.append(spec) try: spec = Spec(*specs) except ValueError as e: raise SpecException(package, d_name, spec) if not specs: return None spec = Spec(*specs) return spec
def split_components(package_str): match_spec = re.compile(r'([A-z]+[A-z\d\-_]*)(~|>=|=|==|<=)(v{,1}[\d\.]+)') match = match_spec.match(package_str) if match: name = match.group(1) operator = match.group(2) version = match.group(3) if operator == '=': # There is a mismatch between the way the node.js semver library # and the python sematic_version specify the equals operator. # we accept both, but must convert a single = to == operator = '==' if operator == '~': base_version = Version(version) if base_version.patch: # ~1.1.1 is the same as >=1.1.1 and < 1.2.0 end_version = Version('{major}.{minor}.{patch}'.format( major=base_version.major, minor=base_version.minor +1, patch=0 )) elif base_version.minor: # ~1.1 is the same as >= 1.1 and < 1.2 end_version = Version('{major}.{minor}.0'.format( major=base_version.major, minor=base_version.minor +1 )) else: # ~1 is the same as >= 1.0.0 and < 2 end_version = Version('{major}.0.0'.format( major=base_version.major +1 )) spec = Spec('>={start},<{end}'.format(start=base_version, end=end_version)) else: spec = Spec(operator+version) return name, spec else: log.error('Invalid package specification %s', package_str) log.info( 'Package specifications must be of the form name~version where' ' ~ is an operator and version is a version number according to ' 'the semver spec (http://semver.org/)' )
def supported_solc_version(solc_version): if solc_version not in Spec( '>=0.4.1,<=0.4.17,!=0.4.10,!=0.4.3,!=0.4.4,!=0.4.5'): raise AssertionError( "Unsupported compiler version: {0}".format(solc_version)) return solc_version
def test_semver_caret(): spec = Spec('^1.0.0') assert (Version('1.1.0') in spec) assert (Version('1.1.0-alpha') not in spec) assert (Version('2.0.0') not in spec) assert (Version('2.0.0-alpha') not in spec)
def resolve_template(self, identifier: Union[str, BaseTemplate], **kwargs) -> Optional[BaseTemplate]: if isinstance(identifier, str): kwargs['name'] = identifier elif isinstance(identifier, BaseTemplate): kwargs['orig'] = identifier query = BaseTemplate.create_query(**kwargs) logger(__name__).info(f'Query: {query}') logger(__name__).debug(query.__dict__) templates = self.resolve_templates(query, **kwargs) logger(__name__).info(f'Candidates: {", ".join([str(t) for t in templates])}') if not any(templates): return None query.version = str(Spec(query.version or '>0').select([Version(t.version) for t in templates])) logger(__name__).info(f'Resolved to {query.identifier}') templates = self.resolve_templates(query, **kwargs) if not any(templates): return None # prefer local templates first local_templates = [t for t in templates if isinstance(t, LocalTemplate)] if any(local_templates): # there's a local template satisfying the query if len(local_templates) > 1: # This should never happen! Conductor state must be invalid raise Exception(f'Multiple local templates satisfy {query.identifier}!') return [t for t in templates if isinstance(t, LocalTemplate)][0] # prefer pros-mainline template second mainline_templates = [t for t in templates if t.metadata['origin'] == 'pros-mainline'] if any(mainline_templates): return mainline_templates[0] # No preference, just FCFS return templates[0]
def _get_spec(self, requirement_name): """ Creates a version range specification from the set of constraints for the required package name. :param str requirement_name: The package name :return Spec: All version specification """ return Spec(','.join(self.versions_spec[requirement_name]))
def device(name, *args, **kwargs): if name in plugin_devices: options = {} # load global configuration settings if available config = kwargs.get("config", default_config) if config: # combine configuration options with keyword arguments. # Keyword arguments take preference, followed by device options, # followed by plugin options, followed by global options. options.update(config["main"]) options.update(config[name.split(".")[0] + ".global"]) options.update(config[name]) kwargs.pop("config", None) options.update(kwargs) # loads the plugin device class plugin_device_class = plugin_devices[name].load() if Version(version()) not in Spec(plugin_device_class.pennylane_requires): raise DeviceError( "The {} plugin requires PennyLane versions {}, however PennyLane " "version {} is installed.".format( name, plugin_device_class.pennylane_requires, __version__ ) ) # load plugin device return plugin_device_class(*args, **options)
def __init__(self, *args, **kwargs): if get_solc_version() not in Spec('>=0.4.11'): raise OSError( "The 'SolcStandardJSONBackend can only be used with solc " "versions >=0.4.11. The SolcCombinedJSONBackend should be used " "for all versions <=0.4.8") super(SolcStandardJSONBackend, self).__init__(*args, **kwargs)
def FOO_SOURCE(supported_solc_version, solc_version): if solc_version in Spec('<0.4.17'): return textwrap.dedent('''\ pragma solidity ^0.4.0; contract Foo { function Foo() {} function return13() public returns (uint) { return 13; } } ''') else: return textwrap.dedent('''\ pragma solidity ^0.4.17; contract Foo { function Foo() public {} function return13() public pure returns (uint) { return 13; } } ''')
def version_in_spec(version: str, spec: str) -> bool: """ Checks if a string version is in a spec :param version: :param spec: :return: """ return Version(version) in Spec(spec)
def is_pyethereum16_available(): pyethereum_version = get_pyethereum_version() if pyethereum_version is None: return False elif pyethereum_version not in Spec('>=1.6.0,<1.7.0'): return False else: return True
def is_pyethereum21_available(): pyethereum_version = get_pyethereum_version() if pyethereum_version is None: return False elif pyethereum_version not in Spec('>=2.1.0,<2.2.0'): return False else: return True
def default_spec(self, manager): """ Given the current release-lines structure, return a default Spec. Specifics: * For feature-like issues, only the highest major release is used, so given a ``manager`` with top level keys of ``[1, 2]``, this would return ``Spec(">=2")``. * When ``releases_always_forwardport_features`` is ``True``, that behavior is nullified, and this function always returns the empty ``Spec`` (which matches any and all versions/lines). * For bugfix-like issues, we only consider major release families which have actual releases already. * Thus the core difference here is that features are 'consumed' by upcoming major releases, and bugfixes are not. * When the ``unstable_prehistory`` setting is ``True``, the default spec starts at the oldest non-zero release line. (Otherwise, issues posted after prehistory ends would try being added to the 0.x part of the tree, which makes no sense in unstable-prehistory mode.) """ # TODO: I feel like this + the surrounding bits in add_to_manager() # could be consolidated & simplified... specstr = "" # Make sure truly-default spec skips 0.x if prehistory was unstable. stable_families = manager.stable_families if manager.config.releases_unstable_prehistory and stable_families: specstr = ">={}".format(min(stable_families)) if self.is_featurelike: # TODO: if app->config-><releases_always_forwardport_features or # w/e if True: specstr = ">={}".format(max(manager.keys())) else: # Can only meaningfully limit to minor release buckets if they # actually exist yet. buckets = self.minor_releases(manager) if buckets: specstr = ">={}".format(max(buckets)) return Spec(specstr) if specstr else Spec()
def _fetch_latest_nextcloud(major: int, curver: Optional[Version]) -> Optional[Nextcloud]: versions = _get_nextcloud_versions() if curver is None: version = Spec(f'^{major}').select(versions.keys()) else: spec = Spec(f'<{curver.next_major()},>{_strip_build(curver)}') version = spec.select(versions.keys()) if version is None: return None url = versions[version] sha_response = download_pbar(url + '.sha256', desc='Fetching checksum for ' + url) sha256: str = sha_response.split(maxsplit=1)[0].decode() ziphash: Sha256 = _hash_zip(url, Sha256(sha256)) nc = Nextcloud(version, url, ziphash) return _update_with_real_version(nc)
def __init__(self, *args, **kwargs): if get_solc_version() not in Spec('<=0.4.8'): raise OSError( "The 'SolcCombinedJSONBackend can only be used with solc " "versions <=0.4.8. The SolcStandardJSONBackend should be used " "for all versions >=0.4.9") warn_msg = 'Support for solc <0.4.11 will be dropped in the next populus release' warnings.warn(warn_msg, DeprecationWarning) super(SolcCombinedJSONBackend, self).__init__(*args, **kwargs)
def _resolve( self, analyzer_name: AnalyzerName, spec_string: str ) -> Optional[Version]: if analyzer_name not in self._data: return None all_versions = [ version for version in self._data[analyzer_name].versions.keys() ] return Spec(spec_string).select(all_versions)
def get_frozen_packages(frozen_packages, server, traits): output = set() for name, version in frozen_packages.iteritems(): spec = Spec('==' + version) best = server.best(name, spec, traits, False) if not best: raise Exception("Could not satisfy {0} Version {1}".format( name, spec)) output.add(best) return output
def find_ide(version='>0.0.0', hint=None, interactive=True): print 'Searching for SC versions matching %s...' % version versions = find_sc_versions(hint=hint) try: version_spec = Spec(version) except ValueError: version_spec = Spec('==' + version) matches = list() for v in versions: semver = versions[v] if version_spec.match(semver): matches.append(v) if matches: best_match_ver = version_spec.select(map(lambda m: versions[m], matches)) for m in matches: if best_match_ver is versions[m]: best_match = m break if interactive and len(matches) > 1: best_num = -1 for i, match in enumerate(matches): print "[%s] %s (%s)" % (i, match, versions[match]) if match == best_match: best_num = i selection = None while not(selection): selection = raw_input("Which ide do you want to use for this project? [default: %s]: " % best_num) if not(selection): selection = best_num try: selection = int(selection) selected_path = matches[selection] return selected_path except Exception: selection = None pass else: return matches[0]
def parse_constraints(self, constraints): if not isinstance(constraints, list): constraints = constraints.replace(', ', ',') else: constraints = ','.join(constraints) if constraints not in self.__class__._constraints: specs = Spec(constraints) self.__class__._constraints[constraints] = specs return self.__class__._constraints[constraints]
def __init__(self, name, version, author=None, description=None, intents=[], env=[]): """Initialize a new Skill. :param name: Name of the skill :type name: str :param version: Version of the skill :type version: str :param author: Author of the skill :type author: str :param description: Optional description of the skill :type description: str :param intents: List of intents supported by this skill :type intents: list :param env: List of configuration variables needed by this skill :type env: list """ super(SkillClient, self).__init__(name='sdk') self.name = name self.author = author self.version = version self.description = description self.intents = intents self.env = env self._version_specs = Spec(__version_requirements__) self._translations = {} self.log.info('Created skill %s\n\t%s' % (self, '\n\t'.join([s.__str__() for s in self.env]))) self._load_translations()
def _get_latest_release_for_app( nc_version: Version, releases: List[Dict[str, Any]], constraint: Optional[Spec]) -> Optional[Dict[str, Any]]: latest: Optional[Dict[str, Any]] = None for release in releases: if '-' in release['version'] or release['isNightly']: continue version = Version(release['version']) if constraint is not None and not constraint.match(version): continue spec = Spec(*release['rawPlatformVersionSpec'].split()) if not spec.match(nc_version): continue if latest is None or Version(latest['version']) < version: latest = release return latest
def __init__(self): if not is_pyethereum16_available(): version = get_pyethereum_version() if version is None: raise pkg_resources.DistributionNotFound( "The `ethereum` package is not available. The " "`PyEthereum16Backend` requires a 1.6.x version of the " "ethereum package to be installed.") elif version not in Spec('>=1.6.0,<1.7.0'): raise pkg_resources.DistributionNotFound( "The `PyEthereum16Backend` requires a 1.6.x version of the " "`ethereum` package. Found {0}".format(version)) self.reset_to_genesis()
def check_installation(): """ This is a little helper that mus be executed before everything else just to check if all dependencies are according to the expected. The docker version is gotten from console and not from docker-py interface because if it is too old the docker-py will fail """ docker_py_version = Spec('<1.6.0') docker_version = Spec('<=1.5.0') if docker_py_version.match(Version(docker.__version__)): logger.error(("Docker-py version must be >= 1.6.0 and yours is %s," " please install the proper one"), docker.__version__) raise Exception("docker-py version < 1.6.0") logger.info("Docker-py version %s", docker.__version__) out, _ = subprocess.Popen(["docker", "--version"], stdout=subprocess.PIPE).communicate() res = re.search(r".*(\d+\.\d+\.\d+).*", out) if res: if docker_version.match(Version(res.group(1).strip())): logger.error(("Docker version must be > 1.5.0," " please install/upgrade to the proper one")) raise Exception("docker version <= 1.5.0") logger.info("Docker version %s", res.group(1).strip()) else: raise Exception("Docker version could not be determined")
def iter_component_providers(self, comp, subs=False, vers=False, reqs="*"): """An iterater function to interate providers of a component Takes a conponent name and yeilds providers of the conponent if `subs` is `True` yeilds providers of subtypes too if `vers` is `True` yeilds all version of the provider not just the highest `reqs` is a version requirement for the providers to meet. Defaults to any version yeilds tuples that look like: `(<component_name>, <plugin_name>, <version>)` Examples: >>> for t in iter_component_providers("foo", subs=True): print(t); ("foo", "foo_plugin", "0.1.0") ("foo", "foo_plugin2", "1.0.0") ("foo.a", "foo.a_plugin", "0.1.0") ("foo.a.b", "footastic", "10.0.0") Args: comp (str): component name to use as a base subs (bool): should subtypes be yeilded too? vers (bool): should all version be yeilded not just the highest? reqs (str, list, tuple): version spec string or list there of all items are passed to a `Spec` Raises: TypeError: if `comp` or `reqs` are passed wrong """ if isinstance(reqs, basestring): reqs = (reqs,) if not isinstance(reqs, (list, tuple)): raise TypeError( "Invalid requierment type, must be string, list, or tuple: %r" % (reqs,)) if not isinstance(comp, basestring): raise TypeError( "comp is niether a Component instance nor a string: %r" % (comp,)) spec = Spec(*reqs) if subs: comps = self.component_map.keys() else: comps = (comp,) for com in comps: if com in self.component_map and issubcomponent(com, comp): providers = self.component_map[com] for prov in providers: versions = providers[prov] if vers: for ver in sorted(versions): yield (com, prov, ver) else: yield (com, prov, spec.select(versions))
def __init__(self, name, spec): self.name = name self.spec_string = spec self.spec = Spec(spec) self.required_by = []