Commit e26a010b authored by Mickaël Desfrênes's avatar Mickaël Desfrênes
Browse files

add download proc

parent 6012a112
Loading
Loading
Loading
Loading
+1
Changes for pyproject.toml: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@ authors = [
dependencies = [
    "typer>=0.12.3",
    "pyinstaller>=6.9.0",
    "requests>=2.32.3",
]
readme = "README.md"
requires-python = ">= 3.12"
−2
Changes for src/climax/__init__.py: 0 added lines, 2 removed lines.
Original line number Diff line number Diff line
def hello() -> str:
    return "Hello from tiper!"
+152 −16
Changes for src/climax/__main__.py: 152 added lines, 16 removed lines.
Original line number Diff line number Diff line
from pathlib import Path
from typing import Optional, Union
from typing_extensions import Annotated
import gettext
import requests
import os
import hashlib
import json
import typer
from rich import print
from rich.progress import track
import shutil

USER_DIR = Path(Path.home(), ".climax")
USER_DIR.mkdir(exist_ok=True)
CACHE_DIR = Path(USER_DIR, "cache")
CACHE_DIR.mkdir(exist_ok=True)
CLIMAX_CONFIG_FILE = ".climax_config.json"
BASEX_DISTRO = "https://files.basex.org/releases/11.1/BaseX111.zip"
SAXON_DISTRO = (
    "https://repo1.maven.org/maven2/net/sf/saxon/Saxon-HE/10.8/Saxon-HE-10.8.jar"
)
MAX_DISTRO = "https://git.unicaen.fr/chauveau/max-v2-basex-poc/-/archive/master/max-v2-basex-poc-master.zip"

locales_dir = Path(__file__).parent / "locales"
# print(locales_dir)
gettext.bindtextdomain("messages", str(locales_dir))
gettext.textdomain("messages")
_ = gettext.gettext


import typer
import time
from rich import print
from rich.progress import track
app = typer.Typer()


app = typer.Typer()
def fetch_config_file() -> Path:
    climax_config_file = Path(os.getcwd(), CLIMAX_CONFIG_FILE)
    if not climax_config_file.exists():
        print(
            "[red]{}[/red]".format(
                _(
                    "Ce dossier n'est pas géré par cliMaX. Êtes-vous sur d'être dans le dossier d'une instance de MaX ?"
                )
            )
        )
        raise typer.Exit(code=1)
    else:
        return climax_config_file


def read_climax_config() -> dict:
    climax_config_file = fetch_config_file()
    with open(climax_config_file, "r") as f:
        config = json.load(f)
        return config


def write_climax_config(data: dict) -> bool:
    climax_config_file = fetch_config_file()
    with open(climax_config_file, "w") as f:
        json.dump(data, f)
        return True


@app.command(help=_("Ceci est un texte d'aide"))
def hello(name: str):
    for i in track(range(5), description=_("En cours...")):
        time.sleep(0.2)
    print(f"hello [green]{name}[/green]")
    print({"tutu": "titi"})
    print(_("error"))
    raise ValueError("no no no no...")
def unzip(source: Union[Path, str], destination: Union[Path, str]) -> bool:
    shutil.unpack_archive(source, destination)
    os.remove(source)
    return True


def cached_download(
    source: str, destination: Union[Path, str], chunk_size: int = 1024
) -> bool:
    cache_path = Path(CACHE_DIR, hashlib.sha1(source.encode("utf-8")).hexdigest())
    if cache_path.exists():
        shutil.copy(cache_path, destination)
    else:
        response = requests.get(source, stream=True)
        if response.status_code != 200:
            print("[red]{}[/red] {}".format(_("Impossible de télécharger"), source))
            raise typer.Exit(code=1)
        total_size = int(response.headers["Content-length"])
        seq_len = total_size // chunk_size
        with open(cache_path, "wb") as f:
            for data in track(
                response.iter_content(chunk_size=chunk_size),
                total=seq_len,
                description=source,
            ):
                f.write(data)
        shutil.copy(cache_path, destination)
    return True


def ensure_new_max_directory(directory: Optional[Path]) -> Path:
    if not directory:
        directory = os.getcwd()
    directory = Path(directory)
    if not directory.exists():
        directory.mkdir(parents=True, exist_ok=False)
    directory = directory.resolve()
    is_empty = not any(directory.iterdir())
    if not is_empty:
        print(
            f"[red]{_("Le dossier n'est pas vide, veuillez en choisir un autre.")}[/red]"
        )
        raise typer.Exit(code=1)
    return directory


@app.command(help=_("Initialisation d'une instance de MaX"))
def init(
    directory: Annotated[
        Optional[Path], typer.Argument(help=_("chemin vers un dossier"))
    ] = os.getcwd(),
    http_port: int = typer.Option(8080, help=_("port du serveur web")),
    basex_port: int = typer.Option(1984, help=_("port du serveur basex")),
):
    root_directory = ensure_new_max_directory(directory)

    print(
        "[bold]"
        + _("Initialisation d'une instance de MaX dans {}").format(root_directory)
        + "[/bold]"
    )

    dot_max_dir = Path(root_directory, ".max")
    dot_max_dir.mkdir(parents=True, exist_ok=False)
    basex_zip_destination = Path(dot_max_dir, "BaseX.zip")
    cached_download(BASEX_DISTRO, basex_zip_destination)
    unzip(basex_zip_destination, dot_max_dir)
    saxon_zip_destination = Path(
        dot_max_dir, "basex", "lib", "custom", "Saxon-HE-10.8.jar"
    )
    cached_download(SAXON_DISTRO, saxon_zip_destination)
    cli_config = {
        "http_port": http_port,
        "basex_port": basex_port,
        "basex_distro": BASEX_DISTRO,
        "saxon_distro": SAXON_DISTRO,
        "max_distro": MAX_DISTRO,
    }
    with open(Path(root_directory, CLIMAX_CONFIG_FILE), "w") as f:
        json.dump(cli_config, f, indent=2)

    with open(Path(root_directory, ".gitignore"), "w") as f:
        f.write(".max\n")

    print(
        "[bold]"
        + _("L'instance de MaX est prête dans {}").format(root_directory)
        + "[/bold]"
    )
    if typer.confirm(
        _("Voulez-vous afficher le dossier {} ?").format(root_directory), default=True
    ):
        typer.launch(str(root_directory), locate=True)


@app.command()
def clear_cache():
    for p in CACHE_DIR.iterdir():
        if p.is_file():
            p.unlink(missing_ok=True)


@app.command()
def goodbye(name: str):
    print(f"goodbye [green]{name}[/green]")
def config_get():
    config = read_climax_config()
    print(config)


if __name__ == "__main__":
+6
Changes for src/climax/locales/en/LC_MESSAGES/messages.po: 6 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -4,3 +4,9 @@ msgstr ""

msgid "Ceci est un texte d'aide"
msgstr "This is a help text"

msgid "Le dossier n'est pas vide, veuillez en choisir un autre."
msgstr "The folder is not empty, please choose another one."

msgid "Initialisation d'une instance de MaX"
msgstr "New MaX instance initialization"
 No newline at end of file
Loading