Skip to content
This repository has been archived by the owner on Dec 27, 2023. It is now read-only.

Commit

Permalink
working htmx commands with cappa
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobi-De committed Nov 21, 2023
1 parent fb3a0ee commit d6d1620
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 76 deletions.
35 changes: 14 additions & 21 deletions fuzzy_couscous/commands/htmx.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@

import cappa
import httpx
from fuzzy_couscous.utils import RICH_ERROR_MARKER
from fuzzy_couscous.utils import RICH_INFO_MARKER
from fuzzy_couscous.utils import RICH_SUCCESS_MARKER
from rich import print as rich_print
from rich.panel import Panel
from rich.progress import Progress
from rich.progress import SpinnerColumn
from rich.progress import TextColumn
Expand All @@ -32,33 +30,28 @@ def __call__(self):
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
msg = f"htmx version {version}"
progress.add_task(f"Downloading {msg} :arrow_down:", total=None)
progress.add_task(f"Downloading htmx version {version}", total=None)
response = httpx.get(url)
except httpx.ConnectError as e:
rich_print(f"{RICH_ERROR_MARKER} Could not connect to {url}")
raise cappa.Exit() from e
raise cappa.Exit(f"Connection error, {url} is not reachable.", code=1) from e

if response.status_code == 404:
msg = f"Could not find {version} version of htmx."
rich_print(f"{RICH_ERROR_MARKER} {msg}")
raise cappa.Exit()
raise cappa.Exit(f"Could not find htmx version {version}.", code=1)

if response.status_code != 200:
rich_print(f"{RICH_ERROR_MARKER} Something went wrong :sad_face: .")
raise cappa.Exit()

# write file to disk

filepath = self.output if self.output.is_file() else self.output / "htmx.min.js"
filepath = self.output if str(self.output).endswith(".js") else self.output / "htmx.min.js"
filepath.write_text(response.content.decode("utf-8"))

subtitle = (
"You are using the latest version of htmx."
if version == latest_version
else f"The latest version available is {latest_version}"
)
rich_print(
f"{RICH_SUCCESS_MARKER} File downloaded successfully to {filepath.name}."
f"\n{RICH_INFO_MARKER} htmx version: {version}"
Panel(
f"[green]htmx version {version} downloaded successfully to {filepath} ![/green]",
subtitle=subtitle,
)
)
if version != latest_version:
rich_print(f"{RICH_INFO_MARKER} The latest version available of htmx version is {latest_version}")

@staticmethod
def get_latest_tag() -> str:
Expand Down
123 changes: 77 additions & 46 deletions fuzzy_couscous/commands/htmx_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,19 @@

import cappa
import httpx
from fuzzy_couscous.utils import RICH_ERROR_MARKER
from rich import print as rich_print
from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress
from rich.progress import SpinnerColumn
from rich.progress import TextColumn
from rich.table import Table

THIRD_PARTY_REGISTRY = {
"htmx-template": {
"download_url": "https://raw.githubusercontent.com/KatrinaKitten/htmx-template/master/htmx-template.min.js",
"info": "https://github.com/KatrinaKitten/htmx-template",
},
"hx-take": {
"download_url": "https://github.com/oriol-martinez/hx-take/blob/main/dist/hx-take.min.js",
"info": "https://github.com/oriol-martinez/hx-take",
},
}

REGISTRY_URL = "https://htmx-extensions.oluwatobi.dev/extensions.json"

@cappa.command(help="Download one of htmx extensions.")

@cappa.command(help="Download one of htmx extensions.", name="htmx-ext")
class HtmxExtension:
name: Annotated[
str | None,
Expand All @@ -27,18 +24,15 @@ class HtmxExtension:
help="The name of the extension to download.",
),
]
version: str = cappa.Arg(
"latest",
short="-v",
long="--version",
help="The version of htmx to use to look for the extension.",
)
output: Path = cappa.Arg(
default=Path.cwd(),
help="The directory to write the downloaded file to.",
short="-o",
long="--output",
)
output: Annotated[
Path,
cappa.Arg(
default=Path(),
help="The directory to write the downloaded file to.",
short="-o",
long="--output",
),
]

def __call__(self) -> None:
if self.name:
Expand All @@ -47,30 +41,67 @@ def __call__(self) -> None:
self.list_all()

def download(self):
metadata = self.registry().get(self.name, {})
if not metadata:
rich_print(f"{RICH_ERROR_MARKER} Could not find extension {self.name}.")
raise cappa.Exit()

download_url = metadata.get("download_url")
response = httpx.get(download_url)
if self.output.is_file():
self.output.unlink(missing_ok=True)
self.output.touch()
self.output.write_text(response.text)
else:
self.output.mkdir(parents=True, exist_ok=True)
(self.output / f"{self.name}.js").write_text(response.text)
extensions = self.read_registry()
extension = extensions.get(self.name)

if not extension:
raise cappa.Exit(f"Could not find {self.name} extension.", code=1)

with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
progress.add_task(
description="Downloading",
total=None,
)
download_url = extension.get("download_url")
response = httpx.get(download_url, follow_redirects=True)

if str(self.output).endswith(".js"):
self.output.write_text(response.text)
else:
self.output.mkdir(parents=True, exist_ok=True)
(self.output / f"{self.name}.js").write_text(response.text)

rich_print(
Panel(
f"[green]Extension {self.name} downloaded successfully![/green]",
subtitle=extension.get("repo_url"),
)
)

def list_all(self):
all_extensions = list(self.registry().keys())
rich_print("\n".join(all_extensions))
extensions = self.read_registry()

table = Table(
title="Htmx Extensions",
caption="Full details at https://htmx-extensions.oluwatobi.dev",
show_lines=True,
)

table.add_column("Name", style="green")
table.add_column("Description", style="magenta")

for name, metadata in extensions.items():
table.add_row(name, metadata.get("description", ""))

def registry(self):
return THIRD_PARTY_REGISTRY | self.official_registry(self.version)
console = Console()
console.print(table)

@classmethod
def official_registry(cls, htmx_version: str):
base_url = f"https://unpkg.com/htmx.org@{htmx_version}/dist/ext/" # noqa
# scrape the site to get the list of extensions
return {}
def read_registry(cls):
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
progress.add_task(
description="Loading extensions registry",
total=None,
)
response = httpx.get(REGISTRY_URL)
if response.status_code != 200:
raise cappa.Exit("Could not read registry, check your connection.", code=1)
return response.json()
1 change: 0 additions & 1 deletion fuzzy_couscous/commands/make.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from ..utils import RICH_SUCCESS_MARKER
from ..utils import write_toml

__all__ = ["Make"]

try:
from enum import StrEnum
Expand Down
4 changes: 1 addition & 3 deletions fuzzy_couscous/commands/rm_migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
import cappa
from rich import print as rich_print

from ..utils import RICH_SUCCESS_MARKER


@cappa.command(help="Remove all migrations for the specified applications directory, intended only for development.")
class RmMigrations:
Expand All @@ -22,4 +20,4 @@ def __call__(self):
if file.suffix == ".py" and file.name not in ["__init__.py"]:
file.unlink()
apps_ = ", ".join(apps)
rich_print(f"{RICH_SUCCESS_MARKER} Removed migration files for apps: {apps_}")
rich_print(f"[green] Removed migration files for apps: {apps_}")
2 changes: 1 addition & 1 deletion fuzzy_couscous/commands/work.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def __call__(

user_commands = {k: _update_command_with_venv(venv_dir, v) for k, v in user_commands.items()}

commands.update(user_commands)
commands |= user_commands

manager = HonchoManager()

Expand Down
3 changes: 1 addition & 2 deletions fuzzy_couscous/commands/write_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from rich.prompt import Prompt

from ..utils import get_current_dir_as_project_name
from ..utils import RICH_SUCCESS_MARKER


@cappa.command(help="Update or create a .env file from a .env.template file.")
Expand Down Expand Up @@ -64,4 +63,4 @@ def __call__(
export=False,
encoding="utf-8",
)
rich_print(f"{RICH_SUCCESS_MARKER} {env_file} file generated")
rich_print(f"[green] {env_file} file generated[/green]")
4 changes: 2 additions & 2 deletions fuzzy_couscous/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ class Cuzzy:
subcommand: cappa.Subcommands[Make | Htmx | HtmxExtension | RmMigrations | RmPoetry | Work | WriteEnv]


def main():
def cli():
cappa.invoke(Cuzzy)


if __name__ == "__main__":
main()
cli()

0 comments on commit d6d1620

Please sign in to comment.