|
3 | 3 | __author__ = "Lukas Heumos"
|
4 | 4 | __email__ = "lukas.heumos@posteo.net"
|
5 | 5 | __version__ = "0.1.0"
|
| 6 | + |
| 7 | +import json |
| 8 | +import logging |
| 9 | +import sys |
| 10 | +import urllib.request |
| 11 | +from logging import Logger |
| 12 | +from subprocess import PIPE, Popen, check_call |
| 13 | +from urllib.error import HTTPError, URLError |
| 14 | + |
| 15 | +from pkg_resources import parse_version |
| 16 | +from rich import print |
| 17 | + |
| 18 | +from pypi_latest.questionary import custom_questionary |
| 19 | + |
| 20 | +log: Logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class PypiLatest: |
| 24 | + """Responsible for checking for newer versions and upgrading it if required.""" |
| 25 | + |
| 26 | + def __init__(self, package_name: str, latest_local_version: str): |
| 27 | + """Constructor for PypiLatest.""" |
| 28 | + self.package_name = package_name |
| 29 | + self.latest_local_version = latest_local_version |
| 30 | + |
| 31 | + def check_upgrade(self) -> None: |
| 32 | + """Checks whether the locally installed version of the package is the latest. |
| 33 | +
|
| 34 | + If not it prompts whether to upgrade and runs the upgrade command if desired. |
| 35 | + """ |
| 36 | + if not PypiLatest.check_latest(self): |
| 37 | + if custom_questionary(function="confirm", question="Do you want to upgrade?", default="y"): |
| 38 | + PypiLatest.upgrade(self) |
| 39 | + |
| 40 | + def check_latest(self) -> bool: |
| 41 | + """Checks whether the locally installed version of the package is the latest available on PyPi. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + True if locally version is the latest or PyPI is inaccessible, False otherwise |
| 45 | + """ |
| 46 | + sliced_local_version = ( |
| 47 | + self.latest_local_version[:-9] |
| 48 | + if self.latest_local_version.endswith("-SNAPSHOT") |
| 49 | + else self.latest_local_version |
| 50 | + ) |
| 51 | + log.debug(f"Latest local {self.package_name} version is: {self.latest_local_version}.") |
| 52 | + log.debug(f"Checking whether a new {self.package_name} version exists on PyPI.") |
| 53 | + try: |
| 54 | + # Retrieve info on latest version |
| 55 | + # Adding nosec (bandit) here, since we have a hardcoded https request |
| 56 | + # It is impossible to access file:// or ftp:// |
| 57 | + # See: https://stackoverflow.com/questions/48779202/audit-url-open-for-permitted-schemes-allowing-use-of-file-or-custom-schemes |
| 58 | + req = urllib.request.Request(f"https://pypi.org/pypi/{self.package_name}/json") # nosec |
| 59 | + with urllib.request.urlopen(req, timeout=1) as response: # nosec |
| 60 | + contents = response.read() |
| 61 | + data = json.loads(contents) |
| 62 | + latest_pypi_version = data["info"]["version"] |
| 63 | + except (HTTPError, TimeoutError, URLError): |
| 64 | + print( |
| 65 | + f"[bold red]Unable to contact PyPI to check for the latest {self.package_name} version. " |
| 66 | + "Do you have an internet connection?" |
| 67 | + ) |
| 68 | + # Returning true by default, since this is not a serious issue |
| 69 | + return True |
| 70 | + |
| 71 | + if parse_version(sliced_local_version) > parse_version(latest_pypi_version): |
| 72 | + print( |
| 73 | + f"[bold yellow]Installed version {self.latest_local_version} of {self.package_name} is newer than the latest release {latest_pypi_version}!" |
| 74 | + f" You are running a nightly version and features may break!" |
| 75 | + ) |
| 76 | + elif parse_version(sliced_local_version) == parse_version(latest_pypi_version): |
| 77 | + return True |
| 78 | + else: |
| 79 | + print( |
| 80 | + f"[bold red]Installed version {self.latest_local_version} of {self.package_name} is outdated. Newest version is {latest_pypi_version}!" |
| 81 | + ) |
| 82 | + return False |
| 83 | + |
| 84 | + return False |
| 85 | + |
| 86 | + def upgrade(self) -> None: |
| 87 | + """Calls pip as a subprocess with the --upgrade flag to upgrade the package to the latest version.""" |
| 88 | + log.debug(f"Attempting to upgrade {self.package_name} via pip install --upgrade {self.package_name} .") |
| 89 | + if not PypiLatest.is_pip_accessible(): |
| 90 | + sys.exit(1) |
| 91 | + try: |
| 92 | + check_call([sys.executable, "-m", "pip", "install", "--upgrade", self.package_name]) |
| 93 | + except Exception as e: |
| 94 | + print(f"[bold red]Unable to upgrade {self.package_name}") |
| 95 | + print(f"[bold red]Exception: {e}") |
| 96 | + |
| 97 | + @classmethod |
| 98 | + def is_pip_accessible(cls) -> bool: |
| 99 | + """Verifies that pip is accessible and in the PATH. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + True if accessible, False if not |
| 103 | + """ |
| 104 | + log.debug("Verifying that pip is accessible.") |
| 105 | + pip_installed = Popen(["pip", "--version"], stdout=PIPE, stderr=PIPE, universal_newlines=True) |
| 106 | + (git_installed_stdout, git_installed_stderr) = pip_installed.communicate() |
| 107 | + if pip_installed.returncode != 0: |
| 108 | + log.debug("Pip was not accessible! Attempted to test via pip --version .") |
| 109 | + print("[bold red]Unable to find 'pip' in the PATH. Is it installed?") |
| 110 | + print("[bold red]Run command was [green]'pip --version '") |
| 111 | + return False |
| 112 | + |
| 113 | + return True |
0 commit comments