def version_check(self): """ Checks for updates (should run in a thread to avoid blocking everything else) References: http://code.activestate.com/recipes/577708-check-for-package-updates-on-pypi-works-best-in-pi/ """ try: from pip._vendor.packaging import version import xmlrpc.client pypi = xmlrpc.client.ServerProxy('https://pypi.python.org/pypi') latest = version.parse(pypi.package_releases('moldesign')[0]) current = version.parse(mdt.__version__) if current >= latest: self.version.value = 'Up to date. Latest release: %s' % latest else: self.version.value = ''.join(('New release available! ', '<br><b>Installed:</b> ' '<span style="font-family:monospace">%s</span>' % current, '<br><b>Newest</b>: ' '<span style="font-family:monospace">%s</span> ' % latest, '<br>Install it by running ' '<span style="font-family:monospace">' 'pip install -U moldesign</span> or ' '<span style="font-family:monospace">' 'conda install -U moldesign</span>')) except Exception as e: self.version.value = '<b>Failed update check</b>: %s' % e
def pip_version_check(session): """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ import pip # imported here to prevent circular imports pypi_version = None try: state = load_selfcheck_statefile() current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: resp = session.get( PyPI.pip_json_url, headers={"Accept": "application/json"}, ) resp.raise_for_status() pypi_version = [ v for v in sorted( list(resp.json()["releases"]), key=packaging_version.parse, ) if not packaging_version.parse(v).is_prerelease ][-1] # save that we've performed a check state.save(pypi_version, current_time) pip_version = packaging_version.parse(pip.__version__) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version): logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'pip install --upgrade pip' command." % (pip.__version__, pypi_version) ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
def _get_latest_version_public(pkg_name): """Check for an update to the component from PyPI""" response = requests.get('https://pypi.python.org/pypi/{0}/json'.format(pkg_name)) if response.status_code != 200: raise UpdateCheckError('PyPI returned status code {}.'.format(response.status_code)) response_json = response.json() if not response_json or not response_json['releases']: raise UpdateCheckError('Unable to get version info from PyPI.') parsed_versions = [packaging_version.parse(v) for v in response_json['releases'] if not packaging_version.parse(v).is_prerelease] sorted_versions = sorted(parsed_versions) return sorted_versions[-1] if sorted_versions else None
def get_version(package, url_pattern=URL_PATTERN): """Return version of package on pypi.python.org using json.""" req = requests.get(url_pattern.format(package=package)) version = parse('0') if req.status_code == requests.codes.ok: j = json.loads(req.text.encode(req.encoding)) if 'releases' in j: releases = j['releases'] for release in releases: ver = parse(release) if not ver.is_prerelease: version = max(version, ver) return version
def version(self): """Return version of package on pypi.python.org using json.""" URL_PATTERN = 'https://pypi.python.org/pypi/{package}/json' req = requests.get(URL_PATTERN.format(package=self.name)) version = parse('0') if req.status_code == requests.codes.ok: j = json.loads(req.text.encode(req.encoding)) if 'releases' in j: releases = j['releases'] for release in releases: ver = parse(release) if not ver.is_prerelease: version = max(version, ver) return str(version)
def _get_current_version(pkg_name): # workaround for getting up-to-date distributions # https://github.com/pypa/pip/issues/2695#issuecomment-96380041 pip.utils.pkg_resources = imp.reload(pip.utils.pkg_resources) current_dist = [dist for dist in get_installed_distributions(local_only=True) if dist.key == pkg_name] if not current_dist: raise UpdateCheckError("Component not installed.") return packaging_version.parse(current_dist[0].version)
def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is eagerly formatted as we want it to get logged as if someone # typed this entire message out. sentences = [ (reason, DEPRECATION_MSG_PREFIX + "{}"), (gone_in, "pip {} will remove support for this functionality."), (replacement, "A possible replacement is {}."), (issue, ( "You can find discussion regarding this at " "https://github.com/pypa/pip/issues/{}." )), ] message = " ".join( template.format(val) for val, template in sentences if val is not None ) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
def less_than(new_ver, old_ver, patch=False): if old_ver is None: return True new_ver = str(new_ver).split('.') old_ver = str(old_ver).split('.') if old_ver[0] is None: return True new_major = parse(new_ver[0] or 0) old_major = parse(old_ver[0] or 0) if new_major > old_major: return False if patch: if len(old_ver) == 1 or old_ver[1] is None: return True new_minor = parse('1.0.{}'.format((new_ver[1] if len(new_ver) > 1 else 0) or 0)) old_minor = parse('1.0.{}'.format((old_ver[1] if len(old_ver) > 1 else 0) or 0)) if new_minor > old_minor: return False return True
def pip_version_check(package_finder): """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if installed_version is None: return pip_version = packaging_version.parse(installed_version) remote_version = None try: state = load_selfcheck_statefile() current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "remote_version" in state.state: last_check = datetime.datetime.strptime(state.state["last_check"], SELFCHECK_DATE_FMT) if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60: remote_version = state.state["remote_version"] # Refresh the version if we need to or just see if we need to warn if remote_version is None: try: remote_version = package_finder.find_requirement( InstallRequirement.from_line('pip'), upgrade=True).version except BestVersionAlreadyInstalled: remote_version = pip_version remote_version = remote_version.base_version # save that we've performed a check state.save(remote_version, current_time) if not remote_version == installed_version: # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, remote_version, pip_cmd) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
def check_pypi_stable_version(dist_name): """Return last stable version package from pypi.org :param dist_name: the distribution name :rtype: string :return lastest stable version string (like 1.1.0) """ req = requests.get(URL_PATTERN_INFO_DIST.format(package=dist_name)) version = parse("0") if req.status_code == requests.codes.ok: j = json.loads(req.text) releases = j.get("releases", []) for release in releases: ver = parse(release) if not ver.is_prerelease: version = max(version, ver) else: return False return version
def _get_current_version(pkg_name): # workaround for getting up-to-date distributions # https://github.com/pypa/pip/issues/2695#issuecomment-96380041 pip.utils.pkg_resources = imp.reload(pip.utils.pkg_resources) current_dist = [ dist for dist in get_installed_distributions(local_only=True) if dist.key == pkg_name ] if not current_dist: raise UpdateCheckError("Component not installed.") return packaging_version.parse(current_dist[0].version)
def _get_latest_version_private(pkg_name): """Check for an update to the component from project private PyPI server""" if not PRIVATE_PYPI_URL: raise UpdateCheckError('{} environment variable not set.'.format(PRIVATE_PYPI_URL_ENV_NAME)) response = requests.get(PRIVATE_PYPI_URL + '/simple/' + pkg_name) if response.status_code != 200: raise UpdateCheckError('Private PyPI returned status code {}.'.format(response.status_code)) # Parse the package links from the response pattern_package_links = re.compile(r'href=[\'"]?([^#\'" >]+)') package_links = re.findall(pattern_package_links, response.text) # Get the package versions from the links search_start = '/packages/'+pkg_name+'-' search_end = '.tar.gz' pattern_version = re.compile('%s(.*)%s' % (search_start, search_end)) versions = [re.search(pattern_version, pl).group(1) for pl in package_links] parsed_versions = [packaging_version.parse(v) for v in versions if not packaging_version.parse(v).is_prerelease] sorted_versions = sorted(parsed_versions) latest_version = sorted_versions[-1] if sorted_versions else None return latest_version
def parse_for_info(self): """Parse the wheel's file name according to PEP427. https://www.python.org/dev/peps/pep-0427/#file-name-convention """ parts = self.file_stem.split('-') if len(parts) == 6: name, ver, build, impl, abi, plat = parts build = int(build) elif len(parts) == 5: name, ver, impl, abi, plat = parts build = None version = packaging_version.parse(ver) return WheelInformation(name, version, build, impl, abi, plat)
def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire message out. message = "DEPRECATION: " + reason if replacement is not None: message += " A possible replacement is {}.".format(replacement) if issue is not None: url = "https://github.com/pypa/pip/issues/" + str(issue) message += " You can find discussion regarding this at {}.".format(url) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
def check_requires_python(requires_python): """ Check if the python version in use match the `requires_python` specifier. Returns `True` if the version of python in use matches the requirement. Returns `False` if the version of python in use does not matches the requirement. Raises an InvalidSpecifier if `requires_python` have an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) # We only use major.minor.micro python_version = version.parse(os.environ['PIP_PYTHON_VERSION']) return python_version in requires_python_specifier
def check_requires_python(requires_python): """ Check if the python version in use match the `requires_python` specifier. Returns `True` if the version of python in use matches the requirement. Returns `False` if the version of python in use does not matches the requirement. Raises an InvalidSpecifier if `requires_python` have an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) # We only use major.minor.micro python_version = version.parse('{0}.{1}.{2}'.format(*sys.version_info[:3])) return python_version in requires_python_specifier
def check_requires_python(requires_python): """ Check if the python version in use match the `requires_python` specifier. Returns `True` if the version of python in use matches the requirement. Returns `False` if the version of python in use does not matches the requirement. Raises an InvalidSpecifier if `requires_python` have an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) # We only use major.minor.micro python_version = version.parse('.'.join(map(str, sys.version_info[:3]))) return python_version in requires_python_specifier
def notEquals(version: str, releases: dict) -> dict: vs = version.replace("!", '').replace("=", '').replace(" ", '') rels = {} for i in releases: p = parse(i) if releases[i] == []: continue if not i.startswith( vs ) and not p.is_devrelease and not p.is_postrelease and not p.is_prerelease: rels[i] = releases[i] l = sorted(rels, key=lambda x: rels[x][0]['upload_time']) rels = getVersions(l, releases) return rels
def get_latest_version(data): """ Return the version string of what we think is the latest version. In the data blob from PyPI there is the info->version key which is just the latest in time. Ideally we want the latest non-pre-release. """ if not data.get('releases'): # If there were no releases, fall back to the old way of doing # things with the info->version key. # This feels kinda strange but it has worked for years return data['info']['version'] all_versions = [] for version in data['releases']: v = parse(version) if not v.is_prerelease: all_versions.append((v, version)) all_versions.sort(reverse=True) # return the highest non-pre-release version return str(all_versions[0][1])
def check_requires_python(requires_python): # type: (Optional[str]) -> bool """ Check if the python version in use match the `requires_python` specifier. Returns `True` if the version of python in use matches the requirement. Returns `False` if the version of python in use does not matches the requirement. Raises an InvalidSpecifier if `requires_python` have an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) # We only use major.minor.micro python_version = version.parse(".".join(map(str, sys.version_info[:3]))) return python_version in requires_python_specifier
def check_requires_python(requires_python, version_info): # type: (Optional[str], Tuple[int, ...]) -> bool """ Check if the given Python version matches a "Requires-Python" specifier. :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) python_version = version.parse('.'.join(map(str, version_info))) return python_version in requires_python_specifier
def filter_packages(key, vers): """Filter out a version of package from list. Mainly for tensorflow-gpu where Python 3.8 is supported only from 2.2.0""" if vers is None: return vers if key == "tensorflow-gpu": tmp = [] for v in vers: # in case of tensorflow python 3.8 is supported only from 2.2.0 python_version = ".".join([str(x) for x in sys.version_info[0:3]]) if (parse("2.2.0") <= parse(v) and parse("3.8.0") <= parse(python_version)) or \ parse("3.8.0") > parse(python_version): tmp.append(v) vers = tmp return vers
def check_requires_python(requires_python, version_info): # type: (Optional[str], Tuple[int, ...]) -> bool """ Check if the given Python version matches a `requires_python` specifier. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). Returns `True` if the version of python in use matches the requirement. Returns `False` if the version of python in use does not matches the requirement. Raises an InvalidSpecifier if `requires_python` have an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) python_version = version.parse('.'.join(map(str, version_info))) return python_version in requires_python_specifier
def parse_line_from_requirements(line): """ Normal version specifiers work: >>> parse_line_from_requirements('Django==1.6.0') ('Django', <Version('1.6.0')>) >>> parse_line_from_requirements('Django>=1.6.0') ('Django', <Version('1.6.0')>) >>> parse_line_from_requirements('Django<=1.6.0') ('Django', <Version('1.6.0')>) Version or package versions with spaces around separators work: >>> parse_line_from_requirements(' Django <= 1.6.0') ('Django', <Version('1.6.0')>) Beta and pre-release version work: >>> parse_line_from_requirements('Django<=1.6.0b1') ('Django', <Version('1.6.0b1')>) >>> parse_line_from_requirements('html5lib==1.0b3') ('html5lib', <Version('1.0b3')>) >>> package,version = parse_line_from_requirements('html5lib==1.0b3') >>> print str(version) 1.0b3 >>> Version(str(version)) <Version('1.0b3')> Invalid requirements-lines returns None: >>> parse_line_from_requirements('Django 1.6.0b1') (None, None) >>> parse_line_from_requirements('Django') (None, None) """ split_result = re.split('[==|<=|>=]+', line) if len(split_result) != 2: return None, None package, version = split_result parsed_version = parse(version.strip()) return package.strip(), parsed_version
def get_updates(requirement, legacy_versions, pre_releases, index_urls): """ Get all updates for passed requirement. :param requirement: :type: pip.req.req_install.InstallRequirement :param legacy_versions: allow legacy versions (f.ex. 0.1dev-r1716') :type: bool :param pre_releases: allow pre-releases (beta, alpha etc.) :type: bool :param index_urls: urls of indices :type: list :rtype: list(str) """ versions = get_versions(requirement.name, index_urls) if not versions: logger.error('No versions found for %s', requirement.name) return [] updates = [] for version in versions: try: version = parse(version) except InvalidVersion: logger.error('Cannot parse version: %s', version) continue if not legacy_versions and isinstance(version, LegacyVersion): continue if not pre_releases and version.is_prerelease: continue if is_update(requirement, version): updates.append(version) return updates
def __init__(self): super(ChangeLog, self).__init__(orientation='vertical') try: current = version.parse(mdt.__version__) latest = self.version_check() if current >= latest: versiontext = 'Up to date. Latest release: %s' % latest else: versiontext = ( 'New release available! ' '(Current: %s, latest: %s <br>' % (current, latest) + '<b>Install it:</b> ' '<span style="font-family:monospace">pip install -U moldesign' '</span>') except Exception as e: versiontext = '<b>Failed update check</b>: %s' % e self.version = ipy.HTML(versiontext) self.textarea = ipy.Textarea(width='700px', height='300px') p1 = os.path.join(mdt.PACKAGEPATH, "HISTORY.rst") p2 = os.path.join(mdt.PACKAGEPATH, "..", "HISTORY.rst") if os.path.exists(p1): path = p1 elif os.path.exists(p2): path = p2 else: path = None if path is not None: with open(path, 'r') as infile: self.textarea.value = infile.read() else: self.textarea.value = 'HISTORY.rst not found' self.textarea.disabled = True self.children = (self.version, self.textarea)
def __init__(self): super(ChangeLog, self).__init__(orientation='vertical') try: current = version.parse(mdt.__version__) latest = self.version_check() if current >= latest: versiontext = 'Up to date. Latest release: %s' % latest else: versiontext = ('New release available! ' '(Current: %s, latest: %s <br>' % (current, latest) + '<b>Install it:</b> ' '<span style="font-family:monospace">pip install -U moldesign' '</span>') except Exception as e: versiontext = '<b>Failed update check</b>: %s' % e self.version = ipy.HTML(versiontext) self.textarea = ipy.Textarea(width='700px', height='300px') p1 = os.path.join(mdt.PACKAGEPATH, "HISTORY.rst") p2 = os.path.join(mdt.PACKAGEPATH, "..", "HISTORY.rst") if os.path.exists(p1): path = p1 elif os.path.exists(p2): path = p2 else: path = None if path is not None: with open(path, 'r') as infile: self.textarea.value = infile.read() else: self.textarea.value = 'HISTORY.rst not found' self.textarea.disabled = True self.children = (self.version, self.textarea)
def parse_for_info(self): name, ver = self.file_stem.rsplit('-', 1) return SourceInformation(name, packaging_version.parse(ver))
def pip_self_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return <<<<<<< HEAD pip_version = packaging_version.bbc_parse(installed_version) ======= pip_version = packaging_version.parse(installed_version) >>>>>>> 241b678... create predictions pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"]
def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is finder = PackageFinder( find_links=options.find_links, index_urls=[options.index_url] + options.extra_index_urls, allow_all_prereleases=False, # Explicitly set to False trusted_hosts=options.trusted_hosts, session=session, ) all_candidates = finder.find_all_candidates("pip") if not all_candidates: return pypi_version = str( max(all_candidates, key=lambda c: c.version).version ) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip')): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
def deprecated( *, reason: str, replacement: Optional[str], gone_in: Optional[str], feature_flag: Optional[str] = None, issue: Optional[int] = None, ) -> None: """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. Should be a complete sentence. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises an error if pip's current version is greater than or equal to this. feature_flag: Command-line flag of the form --use-feature={feature_flag} for testing upcoming functionality. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. """ # Determine whether or not the feature is already gone in this version. is_gone = gone_in is not None and parse(current_version) >= parse(gone_in) message_parts = [ (reason, f"{DEPRECATION_MSG_PREFIX}{{}}"), ( gone_in, "pip {} will enforce this behaviour change." if not is_gone else "Since pip {}, this is no longer supported.", ), ( replacement, "A possible replacement is {}.", ), ( feature_flag, "You can use the flag --use-feature={} to test the upcoming behaviour." if not is_gone else None, ), ( issue, "Discussion can be found at https://github.com/pypa/pip/issues/{}", ), ] message = " ".join( format_str.format(value) for value, format_str in message_parts if format_str is not None and value is not None) # Raise as an error if this behaviour is deprecated. if is_gone: raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
def __bool__(self): return (not self.python_min_ver or parse(PYTHON_VERSION) >= parse(self.python_min_ver)) and \ (not self.python_max_ver or parse(PYTHON_VERSION) <= parse(self.python_max_ver))
def __init__(self, pkg_version, name): self.version = version.parse(pkg_version) self.name = name self.system = name in SYSTEM_PACKAGES self.latest = pkg_version
def get_uptodate(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if parse(str(dist.latest_version)) == parse(str(dist.parsed_version)) ]
def pip_self_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime(state.state["last_check"], SELFCHECK_DATE_FMT) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is link_collector = LinkCollector.create( session, options=options, suppress_no_index=True, ) # Pass allow_yanked=False so we don't suggest upgrading to a # yanked version. selection_prefs = SelectionPreferences( allow_yanked=False, allow_all_prereleases=False, # Explicitly set to False ) finder = PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, ) best_candidate = finder.find_best_candidate("pip").best_candidate if best_candidate is None: return pypi_version = str(best_candidate.version) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) local_version_is_older = ( pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip')) # Determine if our pypi_version is older if not local_version_is_older: return # We cannot tell how the current pip is available in the current # command context, so be pragmatic here and suggest the command # that's always available. This does not accommodate spaces in # `sys.executable`. pip_cmd = "{} -m pip".format(sys.executable) logger.warning( "You are using pip version %s; however, version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) <<<<<<< HEAD python_version = version.bbc_parse('.'.join(map(str, version_info))) ======= python_version = version.parse('.'.join(map(str, version_info))) >>>>>>> 241b678... create predictions return python_version in requires_python_specifier def get_metadata(dist): # type: (Distribution) -> Message """ :raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None. """ metadata_name = 'METADATA' if (isinstance(dist, pkg_resources.DistInfoDistribution) and dist.has_metadata(metadata_name)): metadata = dist.get_metadata(metadata_name) elif dist.has_metadata('PKG-INFO'):
def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime(state.state["last_check"], SELFCHECK_DATE_FMT) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is finder = PackageFinder( find_links=options.find_links, index_urls=[options.index_url] + options.extra_index_urls, allow_all_prereleases=False, # Explicitly set to False trusted_hosts=options.trusted_hosts, session=session, ) candidate = finder.find_candidates("pip").get_best() if candidate is None: return pypi_version = str(candidate.version) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip')): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
def process_result_value(self, value, dialect): return parse(value)
def pip_version_check(session): """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if installed_version is None: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = load_selfcheck_statefile() current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime(state.state["last_check"], SELFCHECK_DATE_FMT) if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: resp = session.get( PyPI.pip_json_url, headers={"Accept": "application/json"}, ) resp.raise_for_status() pypi_version = [ v for v in sorted( list(resp.json()["releases"]), key=packaging_version.parse, ) if not packaging_version.parse(v).is_prerelease ][-1] # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
(reason, DEPRECATION_MSG_PREFIX + "{}"), (gone_in, "pip {} will remove support for this functionality."), (replacement, "A possible replacement is {}."), (issue, ( "You can find discussion regarding this at " "https://github.com/pypa/pip/issues/{}." )), ] message = " ".join( template.format(val) for val, template in sentences if val is not None ) ======= # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire message out. message = "DEPRECATION: " + reason if replacement is not None: message += " A possible replacement is {}.".format(replacement) if issue is not None: url = "https://github.com/pypa/pip/issues/" + str(issue) message += " You can find discussion regarding this at {}.".format(url) >>>>>>> 71358189c5e72ee2ac9883b408a2f540a7f5745e # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) <<<<<<< HEAD ======= >>>>>>> 71358189c5e72ee2ac9883b408a2f540a7f5745e warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)