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

update max distro

parent dd610618
Loading
Loading
Loading
Loading
+137 −94
Changes for src/climax/__main__.py: 137 added lines, 94 removed lines.
Original line number Diff line number Diff line
import subprocess
from pathlib import Path
from typing import Optional, Union
from typing import Optional, Union, Dict
from typing_extensions import Annotated
import gettext
from bs4 import BeautifulSoup
from .eggs import get_yolk
from geler import freeze
import geler
import requests
import os
import hashlib
@@ -32,7 +32,17 @@ 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/pdn-certic/max-v2/-/archive/0.0.1-alpha/max-v2-0.0.1-alpha.zip"

MAX_DISTRO = "https://git.unicaen.fr/pdn-certic/max-v2/-/archive/0.0.2-alpha/max-v2-0.0.2-alpha.zip"

VOCABULARY_BUNDLES = {
    "TEI": {
        "name": "max-dumb-tei",
        "url": "https://git.unicaen.fr/pdn-certic/max-dumb-tei/-/archive/0.0.1/max-dumb-tei-0.0.1.zip",
    }
}


CURRENT_MAX_DISTRO_DIR = os.path.splitext(os.path.basename(MAX_DISTRO))[0]
JAVA_DISTROS = {
    "darwin/arm64": "https://download.java.net/java/GA/jdk22.0.2/c9ecb94cd31b495da20a27d4581645e8/9/GPL/openjdk-22.0.2_macos-aarch64_bin.tar.gz",
@@ -44,12 +54,15 @@ WEB_HOST = "localhost"
BASEX_PORT = 1984
STOP_PORT = 8081
CONFIG_INIT_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns="http://certic.unicaen.fr/max/ns/1.0" env="dev" vocabulary-bundle="max-tei-bundle">
<configuration xmlns="http://certic.unicaen.fr/max/ns/1.0" env="dev" vocabulary-bundle="max-dumb-tei">
    <title>untitled</title>
    <languages>
        <language>fr</language>
        <language>en</language>
    </languages>
     <bundles>
        <bundle name="max-dumb-tei" url="https://git.unicaen.fr/pdn-certic/max-dumb-tei/-/archive/0.0.1/max-dumb-tei-0.0.1.zip"/>
    </bundles>
</configuration>"""


@@ -71,12 +84,14 @@ class MaXProjectConfig:
            self.xml_soup = BeautifulSoup(CONFIG_INIT_TEMPLATE, "xml")
        first = self.xml_soup.find()
        if first and first.name != "configuration":
            raise ValueError(f"{self.config_file_path} is not a MaX configuration file")
            raise ValueError(
                _("{} is not a MaX configuration file").format(self.config_file_path)
            )
        conf = self.xml_soup.find("configuration")
        if not conf:
            conf = self.xml_soup.new_tag("configuration")
            conf["env"] = "dev"
            conf["vocabulary-bundle"] = "max-tei-bundle"
            conf["vocabulary-bundle"] = "max-dumb-tei"
            conf["xmlns"] = "http://certic.unicaen.fr/max/ns/1.0"
            self.xml_soup.append(conf)

@@ -94,7 +109,7 @@ class MaXProjectConfig:
    @property
    def vocabulary_bundle(self) -> str:
        conf = self.xml_soup.find("configuration")
        val = conf.get("vocabulary-bundle", "max-tei-bundle")
        val = conf.get("vocabulary-bundle", "max-dumb-tei")
        return str(val)

    @vocabulary_bundle.setter
@@ -143,6 +158,30 @@ class MaXProjectConfig:
            language_tag.string = language
            nodes.append(language_tag)

    @property
    def bundles(self) -> Dict[str, str]:
        vals = {}
        conf = self.xml_soup.find("configuration")
        nodes = conf.find("bundles")
        if nodes:
            for bundle in nodes.find_all("bundle"):
                vals[bundle["name"]] = bundle["url"]
        return vals

    @bundles.setter
    def bundles(self, bundles: Dict[str, str]):
        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():
            bundle_tag = self.xml_soup.new_tag("bundle")
            bundle_tag["name"] = bundle_name
            bundle_tag["url"] = bundle_url
            nodes.append(bundle_tag)

    def __str__(self):
        return self.xml_soup.prettify()

@@ -313,7 +352,30 @@ app = typer.Typer(
)


def _install_new_max_instance(root_directory: Path):
def _sync_bundles(root_directory: Path):
    ignore_file = ".ignore"
    dot_max_dir = Path(root_directory, ".max")
    bundles_dir = Path(dot_max_dir, "basex", "webapp", "max", "bundles")
    # first deactivate everything
    for item in os.listdir(bundles_dir):
        if os.path.isdir(Path(bundles_dir, item)):
            Path(bundles_dir, item, ignore_file).touch()
    config = MaXProjectConfig(Path(root_directory, "config.xml"))
    # then activate or install what is in config file
    for bundle_name, bundle_url in config.bundles.items():
        bundle_dir = Path(bundles_dir, bundle_name)
        if os.path.isdir(bundle_dir):
            Path(bundle_dir, ignore_file).unlink(missing_ok=True)
        else:
            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()


def _install_new_max_instance(root_directory: Path, vocabulary: str = "TEI"):
    print(
        "[bold]"
        + _("Initialisation d'une nouvelle instance de MaX dans {}").format(
@@ -336,60 +398,24 @@ def _install_new_max_instance(root_directory: Path):
    with open(Path(root_directory, ".gitignore"), "w") as f:
        f.write(".max\n")

    os.makedirs(Path(dot_max_dir, "basex", "repo", "max"), exist_ok=True)
    shutil.copytree(
        Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "webapp"),
        Path(dot_max_dir, "basex", "webapp", "max"),
    )
    shutil.copy(
        Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "expath-pkg.xml"),
        Path(dot_max_dir, "basex", "repo", "max", "expath-pkg.xml"),
    )
    shutil.copytree(
        Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "core"),
        Path(dot_max_dir, "basex", "repo", "max", "max"),
        Path(dot_max_dir, "basex", "webapp", "max", "core"),
    )
    shutil.copytree(
        Path(
            USER_DIR,
            "max",
            CURRENT_MAX_DISTRO_DIR,
            "src",
            "main",
            "bundles",
            "max-content-html-bundle",
        ),
        Path(dot_max_dir, "basex", "repo", "max-content-html-bundle"),
    )
    shutil.copytree(
        Path(
            USER_DIR,
            "max",
            CURRENT_MAX_DISTRO_DIR,
            "src",
            "main",
            "bundles",
            "max-autoroute-bundle",
        ),
        Path(dot_max_dir, "basex", "repo", "max-autoroute-bundle"),
        Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "bundles"),
        Path(dot_max_dir, "basex", "webapp", "max", "bundles"),
    )

    # TODO: assuming TEI, but shouldn't we ask first ? Or make this a mandatory argument ?
    shutil.copytree(
        Path(
            USER_DIR,
            "max",
            CURRENT_MAX_DISTRO_DIR,
            "src",
            "main",
            "bundles",
            "max-tei-bundle",
        ),
        Path(dot_max_dir, "basex", "repo", "max-tei-bundle"),
    )
    new_max_config = MaXProjectConfig(config_file_path)
    new_max_config.vocabulary_bundle = "max-tei-bundle"
    if vocabulary in VOCABULARY_BUNDLES.keys():
        vocabulary_bundle = VOCABULARY_BUNDLES.get(vocabulary)
        new_max_config.vocabulary_bundle = vocabulary_bundle.get("name")
        new_max_config.bundles = {
            vocabulary_bundle.get("name"): vocabulary_bundle.get("url")
        }
    new_max_config.write()
    _sync_bundles(root_directory)
    print(
        "[bold]"
        + _("La nouvelle instance de MaX est prête dans {}").format(root_directory)
@@ -412,6 +438,7 @@ def _sync_max_instance(root_directory: Path):
    )
    MaXProjectConfig(Path(root_directory, "config.xml"))
    dot_max_dir = Path(root_directory, ".max")
    if not os.path.isdir(dot_max_dir):
        dot_max_dir.mkdir(parents=True, exist_ok=True)
        basex_zip_destination = Path(dot_max_dir, "BaseX.zip")
        cached_download(BASEX_DISTRO, basex_zip_destination)
@@ -420,47 +447,17 @@ def _sync_max_instance(root_directory: Path):
            dot_max_dir, "basex", "lib", "custom", "Saxon-HE-10.8.jar"
        )
        cached_download(SAXON_DISTRO, saxon_zip_destination)
    os.makedirs(Path(dot_max_dir, "basex", "repo", "max"), exist_ok=True)
    shutil.copytree(
        Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "webapp"),
        Path(dot_max_dir, "basex", "webapp", "max"),
    )
    shutil.copy(
        Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "expath-pkg.xml"),
        Path(dot_max_dir, "basex", "repo", "max", "expath-pkg.xml"),
    )

        shutil.copytree(
            Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "core"),
        Path(dot_max_dir, "basex", "repo", "max", "max"),
    )
    shutil.copytree(
        Path(
            USER_DIR,
            "max",
            CURRENT_MAX_DISTRO_DIR,
            "src",
            "main",
            "bundles",
            "max-content-html-bundle",
        ),
        Path(dot_max_dir, "basex", "repo", "max-content-html-bundle"),
            Path(dot_max_dir, "basex", "webapp", "max", "core"),
        )
        shutil.copytree(
        Path(
            USER_DIR,
            "max",
            CURRENT_MAX_DISTRO_DIR,
            "src",
            "main",
            "bundles",
            "max-autoroute-bundle",
        ),
        Path(dot_max_dir, "basex", "repo", "max-autoroute-bundle"),
            Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "bundles"),
            Path(dot_max_dir, "basex", "webapp", "max", "bundles"),
        )

    #
    # TODO: read vocabulary and bundles list in existing_max_config and install
    #
    _sync_bundles(root_directory)

    print(
        "[bold]"
@@ -469,8 +466,8 @@ def _sync_max_instance(root_directory: Path):
    )


@app.command(help=_("Initialisation d'une instance de MaX"))
def init(
@app.command(help=_("Initialisation d'une instance existante de MaX"))
def sync(
    directory: Annotated[
        Optional[Path], typer.Argument(help=_("chemin vers un dossier"))
    ] = os.getcwd(),
@@ -482,7 +479,29 @@ def init(
    if is_max:
        _sync_max_instance(root_directory)
    else:
        _install_new_max_instance(root_directory)
        print(
            _(
                "Le dossier ne contient pas une instance de MaX. Utiliser la commande new"
            )
        )
        raise typer.Exit()


@app.command(help=_("Création d'une nouvelle instance de MaX"))
def new(
    directory: Annotated[
        Optional[Path], typer.Argument(help=_("chemin vers un dossier"))
    ] = os.getcwd(),
    vocabulary: str = "TEI",
):
    ensure_java()
    ensure_max_distro()
    root_directory, is_max = ensure_available_max_directory(directory)
    if is_max:
        print(_("Le dossier contient une instance de MaX. Utiliser la commande init"))
        raise typer.Exit()
    else:
        _install_new_max_instance(root_directory, vocabulary)


@app.command(
@@ -621,7 +640,7 @@ def config():


@app.command(help=_("Fait une copie HTML statique du projet dans le dossier"))
def mirror(
def freeze(
    directory: Annotated[
        Optional[Path], typer.Argument(help=_("chemin vers un dossier"))
    ] = Path(os.getcwd(), "output"),
@@ -637,7 +656,7 @@ def mirror(
        # for lang in config.languages:
        # start_url = f"http://localhost:{port_number}/{lang}/tdm.html"
        start_url = f"http://localhost:{port_number}/"
        freeze(start_url, directory)
        geler.freeze(start_url, directory)
    except Exception as e:
        stop(stop_port)
        raise e
@@ -646,6 +665,30 @@ def mirror(
    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()
    config = max_config()
    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))
        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()


get_yolk()

if __name__ == "__main__":