Skip to content

Commit

Permalink
feat: plugin update checker and add skip update checker config key
Browse files Browse the repository at this point in the history
  • Loading branch information
THEGOLDENPRO committed Apr 8, 2024
1 parent 3003391 commit e92b6ba
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 23 deletions.
17 changes: 11 additions & 6 deletions mov_cli/cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,23 @@ def mov_cli(
if config.debug:
mov_cli_logger.setLevel(logging.DEBUG)

plugins = config.plugins

print(
welcome_msg(plugins, True if query is None else False, version)
)

mov_cli_logger.debug(f"Config -> {config.data}")

if edit is True:
open_config_file(config)
return None

plugins = config.plugins

welcome_message = welcome_msg(
plugins = plugins,
check_for_updates = True if query is None and config.skip_update_checker is False else False,
display_hint = True if query is None else False,
display_version = version
)

print(welcome_message)

if query is not None:
scrape_options = steal_scraper_args(query)
# This allows passing arguments to scrapers like this:
Expand Down
16 changes: 9 additions & 7 deletions mov_cli/cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from typing import Literal, Tuple, List, NoReturn
from typing import Literal, Tuple, List, NoReturn, Dict

from mov_cli.scraper import ScraperOptionsT

Expand Down Expand Up @@ -57,7 +57,7 @@ def greetings() -> Tuple[Literal["Good Morning", "Good Afternoon", "Good Evening
return greeting, user_name

# This function below is inspired by animdl: https://github.com/justfoolingaround/animdl
def welcome_msg(plugins: Dict[str, str], display_hint: bool = False, display_version: bool = False) -> str:
def welcome_msg(plugins: Dict[str, str], check_for_updates: bool = False, display_hint: bool = False, display_version: bool = False) -> str:
"""Returns cli welcome message."""
now = datetime.now()
adjective = random.choice(
Expand All @@ -78,13 +78,15 @@ def welcome_msg(plugins: Dict[str, str], display_hint: bool = False, display_ver
if display_version is True:
text += f"\n\n{Colours.CLAY}-> {Colours.RESET}Version: {Colours.BLUE}{mov_cli_version}{Colours.RESET}"

if update_available():
text += f"\n\n {Colours.PURPLE}{Colours.ORANGE}An update is available! --> {Colours.RESET}pip install mov-cli -U"
if check_for_updates:

plugin_needs_updating, plugins_to_update = plugin_update_available(plugins)
if update_available():
text += f"\n\n {Colours.PURPLE}{Colours.ORANGE}An update is available! --> {Colours.RESET}pip install mov-cli -U"

if plugin_needs_updating:
text += f"\n\n {Colours.ORANGE}|˶˙ᵕ˙ )ノ゙ {Colours.GREEN}Some plugins need updating! --> {Colours.RESET}pip install {' '.join(plugins_to_update)} -U"
plugin_needs_updating, plugins_to_update = plugin_update_available(plugins)

if plugin_needs_updating:
text += f"\n\n {Colours.ORANGE}|˶˙ᵕ˙ )ノ゙ {Colours.GREEN}Some plugins need updating! --> {Colours.RESET}pip install {' '.join(plugins_to_update)} -U"

return text + "\n"

Expand Down
4 changes: 4 additions & 0 deletions mov_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ def editor(self) -> Optional[str]:
"""Returns the editor that should be opened while editing."""
return self.data.get("editor")

@property
def skip_update_checker(self) -> bool:
return self.data.get("skip_update_checker", False)

@property
def default_scraper(self) -> Optional[str]:
"""Returns the scraper that should be used to scrape by default."""
Expand Down
1 change: 1 addition & 0 deletions mov_cli/config.template.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ player = "mpv"
debug = false
# parser = "lxml"
# editor = "nano"
skip_update_checker = false

[mov-cli.ui]
fzf = true
Expand Down
36 changes: 26 additions & 10 deletions mov_cli/utils/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def update_available() -> bool:

def plugin_update_available(plugins: Dict[str, str]) -> Tuple[bool, List[str]]:
plugins_with_updates: List[str] = []
logger.debug("Checking if plugins need updating...")

for _, module_name in plugins.items():
plugin = load_plugin(module_name)
Expand All @@ -52,26 +53,41 @@ def plugin_update_available(plugins: Dict[str, str]) -> Tuple[bool, List[str]]:
continue

plugin_module = plugin[1]
plugin_version: Optional[int] = getattr(plugin_module, "__version__", None)
plugin_hook_data = plugin[0]

plugin_version: Optional[str] = getattr(plugin_module, "__version__", None)

if plugin_version is None:
logger.debug(
f"Skipped update check for '{module_name}' as the plugin " \
"doesn't expose '__version__' in it's root module ('__init__.py')."
)
continue

logger.debug(f"Checking if the plugin '{module_name}' is up to date...")
pypi_package_name = plugin_hook_data.get("package_name", None)

if pypi_package_name is None:
logger.debug(
f"Skipped update check for '{module_name}' as the plugin " \
"doesn't contain 'package_name' in it's hook data."
)
continue

# NOTE: Welp, this would break for plugins not named consistently but I can't think of a solution rn and it's getting late 😴
pypi_package_name = module_name.replace("_", "-")
response = httpx.get(f"https://pypi.org/pypi/{pypi_package_name}/json")
try:
response = httpx.get(f"https://pypi.org/pypi/{pypi_package_name}/json")
except httpx.HTTPError as e:
logger.warning(f"Failed to check for update of the plugin '{module_name}'! Error: {e}")
continue

if response.status_code > 400:
logger.warning(f"Failed to check pypi version of the plugin '{module_name}'!")
if response.status_code >= 400:
logger.warning(f"Failed to check for update of the plugin '{module_name}'! Response: {response}")
continue

pypi_json = response.json()
pypi_version: int = pypi_json["info"]["version"]
pypi_version: str = pypi_json["info"]["version"]

if pypi_version > plugin_version:
plugins_with_updates.append(module_name)
if version.parse(pypi_version) > version.parse(plugin_version):
plugins_with_updates.append(pypi_package_name)

if not plugins_with_updates == []:
return True, plugins_with_updates
Expand Down

0 comments on commit e92b6ba

Please sign in to comment.