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

fix bundles management, add local bundles

parent 1af21e06
Loading
Loading
Loading
Loading
+92 −39
Changes for src/climax/__main__.py: 92 added lines, 39 removed lines.
Original line number Diff line number Diff line
@@ -3,27 +3,28 @@ from pathlib import Path
from typing import Optional, Union, Dict
from typing_extensions import Annotated
import gettext
from bs4 import BeautifulSoup
from .eggs import get_yolk
import geler
import requests
import os
import hashlib
import platform
import typer
from rich import print
from rich.progress import track
from rich.console import Console
from rich.table import Table
import shutil
from functools import lru_cache
import socket

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

from bs4 import BeautifulSoup  # noqa: E402
from .eggs import get_yolk  # noqa: E402
import geler  # noqa: E402
import requests  # noqa: E402
import os  # noqa: E402
import hashlib  # noqa: E402
import platform  # noqa: E402
import typer  # noqa: E402
from rich import print  # noqa: E402
from rich.progress import track  # noqa: E402
from rich.console import Console  # noqa: E402
from rich.table import Table  # noqa: E402
import shutil  # noqa: E402
from functools import lru_cache  # noqa: E402
import socket  # noqa: E402


WELCOME_PAGE = """
<h1>Bienvenue dans MaX !</h1>
@@ -135,7 +136,7 @@ class MaXProjectConfig:
                        )
                        else False,
                    }
        return available_bundles
        return dict(sorted(available_bundles.items()))

    @property
    def max_version(self) -> str:
@@ -230,17 +231,18 @@ class MaXProjectConfig:
        return vals

    @bundles.setter
    def bundles(self, bundles: Dict[str, str]):
    def bundles(self, bundles: Dict[str, Dict]):
        conf = self.xml_soup.find("configuration")
        nodes = conf.find("bundles")
        if not nodes:
            nodes = self.xml_soup.new_tag("languages")
            conf.append(nodes)
        nodes.clear()
        for bundle_name, bundle_url in bundles.items():
        for bundle_name, bundle_dict in bundles.items():
            bundle_tag = self.xml_soup.new_tag("bundle")
            bundle_tag["name"] = bundle_name
            bundle_tag["url"] = bundle_url
            bundle_tag["name"] = bundle_dict["name"]
            if bundle_dict.get("url"):
                bundle_tag["url"] = bundle_dict["url"]
            nodes.append(bundle_tag)

    def __str__(self):
@@ -428,12 +430,24 @@ def _sync_bundles(root_directory: Path):
        if os.path.isdir(bundle_dir):
            Path(bundle_dir, ignore_file).unlink(missing_ok=True)
        else:
            if str(bundle["url"]).startswith("http://") or str(
                bundle["url"]
            ).startswith("https://"):
                bundle_archive_path = Path(bundles_dir, f"{bundle_name}.zip")
                cached_download(bundle["url"], bundle_archive_path)
                shutil.unpack_archive(bundle_archive_path, bundles_dir)
                dir_name, _ = os.path.splitext(os.path.basename(bundle["url"]))
                Path(bundles_dir, dir_name).rename(bundle_dir)
                bundle_archive_path.unlink()
            if str(bundle["url"]).startswith("local://"):
                zip_name = str(bundle["url"]).lstrip("local://")
                bundle_archive_path = Path(
                    dot_max_dir, "resources", "local_bundles", f"{zip_name}"
                )
                shutil.unpack_archive(bundle_archive_path, bundles_dir)
                dir_name, _ = os.path.splitext(os.path.basename(bundle["url"]))
                Path(bundles_dir, dir_name).rename(bundle_dir)
                bundle_archive_path.unlink()


def _install_new_max_instance(root_directory: Path):
@@ -714,14 +728,6 @@ def freeze(
    print("[green]" + _("Site copié dans {}").format(str(directory)) + "[/green]")


@app.command(help=_("Liste les bundles actifs pour l'instance de Max en cours"))
def bundles_list_active():
    check_cwd_is_max()
    config = max_config()
    for bundle_name, bundle_url in config.bundles.items():
        print(f"{bundle_name} ({bundle_url})")


@app.command(help=_("Supprime un bundle pour l'instance de Max en cours"))
def bundles_remove(bundle_name: str):
    check_cwd_is_max()
@@ -729,26 +735,27 @@ def bundles_remove(bundle_name: str):
    keep_bundles = {}
    bundle_name = bundle_name.lower().strip()
    if bundle_name not in config.bundles.keys():
        print(_("[red]{} n'est pas un bundle actif[red]").format(bundle_name))
        print(_("[red]{} n'est pas un bundle actif[/red]").format(bundle_name))
        raise typer.Exit(code=1)
    for active_bundle_name, active_bundle_url in config.bundles.items():
        if active_bundle_name.strip() != bundle_name.strip():
            keep_bundles[active_bundle_name] = active_bundle_url
    config.bundles = keep_bundles
    config.write()
    bundles_list_available()
    bundles_list()


@app.command(help=_("Liste les bundles disponibles"))
def bundles_list_available():
def bundles_list(installed_only: bool = False):
    check_cwd_is_max()
    config = max_config()
    console = Console()
    table = Table(
        _("Nom"), _("Installé"), _("Description"), _("vocabulaire"), show_lines=True
    )
    for bunle_name, bundle in config.available_bundles.items():
        table.add_row(
    bundles_done = {}
    for bundle_name, bundle in config.available_bundles.items():
        bundles_done[bundle_name] = [
            "[bold]{}[/bold]".format(bundle["name"]),
            "[green]{}[/green]".format(_("oui"))
            if bundle["active"]
@@ -757,20 +764,66 @@ def bundles_list_available():
            "[green]{}[/green]".format(_("oui"))
            if bundle["vocabulary"]
            else "[red]{}[/red]".format(_("non")),
        )
        ]

    for bundle_name, bundle in config.bundles.items():
        if bundle_name not in bundles_done.keys():
            bundles_done[bundle_name] = [
                "[bold]{}[/bold]".format(bundle_name),
                "[green]{}[/green]".format(_("oui")),
                _("(bundle local sans description)"),
                "(inconnu)",
            ]
    for k, row in dict(sorted(bundles_done.items())).items():
        table.add_row(*row)
    console.print(table)


@app.command(help=_("Ajoute un bundle pour l'instance de Max en cours"))
def bundles_add(bundle_name: str, from_archive: str = None):
def bundles_add(bundle_name: str):
    from_archive = None
    check_cwd_is_max()
    config = max_config()
    current_bundles_config = config.bundles
    if from_archive is not None:
        pass  # todo: install from archive
    # bundle_name is a local archive
    if bundle_name.endswith(".zip") and Path(bundle_name).is_file():
        from_archive = bundle_name
        bundle_name = os.path.splitext(os.path.basename(bundle_name))[0]
        print(bundle_name, from_archive)
    if from_archive is not None:  # todo install from archive
        if type(from_archive) is str:
            from_archive = Path(from_archive)
        if not from_archive.is_file():
            print(
                _("[red][bold]{}[/bold] n'est pas un chemin valide[/red]").format(
                    from_archive
                )
            )
            raise typer.Exit(code=1)
        fname, extension = os.path.splitext(from_archive)
        if extension != ".zip":
            print(_("[red]{} n'est pas un bundle[/red]").format(from_archive))
            raise typer.Exit(code=1)
        local_destination = Path(
            os.getcwd(),
            ".max",
            "resources",
            "local_bundles",
            os.path.basename(from_archive),
        )
        Path(os.path.dirname(local_destination)).mkdir(exist_ok=True, parents=True)
        shutil.copy(from_archive, local_destination)
        current_bundles_config[bundle_name] = {
            "name": bundle_name,
            "url": f"local://{os.path.basename(local_destination)}",
        }
        config.bundles = current_bundles_config
        config.write()
        _sync_max_instance(os.getcwd(), verbose=False)
        bundles_list()
    else:
        if bundle_name not in config.available_bundles.keys():
            print(_("[red]{} n'est pas un bundle disponible[red]").format(bundle_name))
            print(_("[red]{} n'est pas un bundle disponible[/red]").format(bundle_name))
            raise typer.Exit(code=1)
        else:
            for (
@@ -784,7 +837,7 @@ def bundles_add(bundle_name: str, from_archive: str = None):
                    config.bundles = current_bundles_config
                    config.write()
                    _sync_max_instance(os.getcwd(), verbose=False)
                    bundles_list_available()
                    bundles_list()


get_yolk()