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

use gitlab API, refactor

parent 51cfca1b
Loading
Loading
Loading
Loading
+85 −75
Changes for src/climax/__main__.py: 85 added lines, 75 removed lines.
Original line number Diff line number Diff line
import subprocess
from pathlib import Path
from typing import Optional, Union, Iterator
from typing import Optional, Union, Iterator, List
from typing_extensions import Annotated
import gettext
import tempfile

locales_dir = Path(__file__).parent / "locales"
gettext.bindtextdomain("messages", str(locales_dir))
@@ -19,13 +20,14 @@ from .config import ( # noqa: E402
    MAX_CONFIG_FILE,
    BASEX_DISTRO,
    SAXON_DISTRO,
    MAX_DISTRO,
    CURRENT_MAX_DISTRO_DIR,
    JAVA_DISTROS,
    WEB_PORT,
    WEB_HOST,
    BASEX_PORT,
    STOP_PORT,
    max_releases,
    max_release,
    latest_max_release,
)
import geler  # noqa: E402
import requests  # noqa: E402
@@ -41,7 +43,7 @@ import shutil # noqa: E402
from functools import lru_cache  # noqa: E402
import socket  # noqa: E402
from .model import db, MaxInstall  # noqa: E402
# from simple_term_menu import TerminalMenu  # noqa: E402
from simple_term_menu import TerminalMenu  # noqa: E402

climax_db = db()

@@ -208,15 +210,6 @@ def ensure_java() -> Path:
    return java_bin


def ensure_max_distro() -> Path:
    destination_folder = Path(USER_MAX_DIR, "max")
    if not destination_folder.exists():
        destination_archive = Path(USER_MAX_DIR, "max.zip")
        cached_download(MAX_DISTRO, destination_archive)
        unzip(destination_archive, destination_folder)
    return destination_folder


def ensure_available_max_directory(directory: Optional[Path]) -> tuple[Path, bool]:
    if not directory:
        directory = os.getcwd()
@@ -278,7 +271,28 @@ def _sync_bundles(root_directory: Path):
                bundle_archive_path.unlink()


def _install_new_max_instance(root_directory: Path):
def _copy_max_tree(
    dot_max_dir: Union[str, Path], max_release_name: str, max_release_url: str
):
    with tempfile.TemporaryDirectory() as tmpdirname:
        zip_destination = Path(tmpdirname, "max.zip")
        cached_download(max_release_url, zip_destination)
        unzip(zip_destination, tmpdirname)
        shutil.copytree(
            Path(tmpdirname, f"max-v2-{max_release_name}", "src", "main", "core"),
            Path(dot_max_dir, "basex", "webapp", "max", "core"),
        )
        shutil.copytree(
            Path(tmpdirname, f"max-v2-{max_release_name}", "src", "main", "bundles"),
            Path(dot_max_dir, "basex", "webapp", "max", "bundles"),
        )
        shutil.copytree(
            Path(tmpdirname, f"max-v2-{max_release_name}", "src", "resources"),
            Path(dot_max_dir, "resources"),
        )


def _install_new_max_instance(root_directory: Path, init_values: dict = None):
    print(
        "[bold]"
        + _("Initialisation d'une nouvelle instance de MaX dans {}").format(
@@ -287,37 +301,29 @@ def _install_new_max_instance(root_directory: Path):
        + "[/bold]"
    )
    config_file_path = Path(root_directory, "config.xml")
    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)

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

    shutil.copytree(
        Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "core"),
        Path(dot_max_dir, "basex", "webapp", "max", "core"),
    )
    shutil.copytree(
        Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "bundles"),
        Path(dot_max_dir, "basex", "webapp", "max", "bundles"),
    )

    shutil.copytree(
        Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "resources"),
        Path(dot_max_dir, "resources"),
    )

    shutil.copy(Path(dot_max_dir, "resources", "config.xml.sample"), config_file_path)
    conf = MaXProjectConfig(config_file_path)
    if init_values is not None:
        conf.title = init_values.get("title", "")
        conf.env = init_values.get("env", "prod")
        conf.max_version = {
            "name": init_values.get("max_version"),
            "url": init_values.get("max_url"),
        }
    else:
        conf.title = "inconnu"
        conf.env = "prod"
        latest_max = latest_max_release()
        conf.max_version = {
            "name": latest_max["name"],
            "url": latest_max["zip_url"],
        }
    conf.write()

    _sync_bundles(root_directory)
    _sync_max_instance(root_directory, verbose=False)

    Path(root_directory, "content_html", "fr").mkdir(exist_ok=True, parents=True)
    welcome_page = Path(root_directory, "content_html", "fr", "index.html")
@@ -346,7 +352,7 @@ def _sync_max_instance(root_directory: Path, verbose=True):
            )
            + "[/bold]"
        )
    MaXProjectConfig(Path(root_directory, "config.xml"))
    config = 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)
@@ -358,18 +364,10 @@ def _sync_max_instance(root_directory: Path, verbose=True):
        )
        cached_download(SAXON_DISTRO, saxon_zip_destination)

        shutil.copytree(
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "core"),
            Path(dot_max_dir, "basex", "webapp", "max", "core"),
        )
        shutil.copytree(
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "main", "bundles"),
            Path(dot_max_dir, "basex", "webapp", "max", "bundles"),
        )

        shutil.copytree(
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "src", "resources"),
            Path(dot_max_dir, "resources"),
        _copy_max_tree(
            Path(root_directory, ".max"),
            config.max_version.get("name"),
            config.max_version.get("url"),
        )

    _sync_bundles(root_directory)
@@ -388,7 +386,6 @@ def sync(
    ] = os.getcwd(),
):
    ensure_java()
    ensure_max_distro()
    root_directory, is_max = ensure_available_max_directory(directory)

    if is_max:
@@ -404,20 +401,34 @@ def sync(
        raise typer.Exit()


def _choose_between(values: List[str], label: str = "") -> str:
    terminal_menu = TerminalMenu(values, title=label)
    menu_entry_index = terminal_menu.show()
    return values[menu_entry_index]


@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(),
    interactive: bool = False,
):
    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 sync"))
        print(_("Le dossier contient une instance de MaX. Utilisez la commande sync"))
        raise typer.Exit()
    else:
        _install_new_max_instance(root_directory)
    init_values = None
    if interactive:
        init_values = {}
        init_values["max_version"] = _choose_between(
            [x["name"] for x in max_releases()], _("Version de max")
        )
        init_values["max_url"] = max_release(init_values["max_version"]).get("zip_url")
        init_values["env"] = _choose_between(["dev", "prod"], _("Environnement"))
        init_values["title"] = typer.prompt(_("Titre du projet"))
    _install_new_max_instance(root_directory, init_values)


@app.command(
@@ -429,35 +440,42 @@ def demo():
        _("Voulez-vous installer une édition de démonstration ?"), default=False
    ):
        cur_dir = os.getcwd()
        config = MaXProjectConfig(Path(cur_dir, "config.xml"))
        with tempfile.TemporaryDirectory() as tmpdirname:
            zip_destination = Path(tmpdirname, "max.zip")
            cached_download(config.max_version["url"], zip_destination)
            unzip(zip_destination, tmpdirname)
            tmp_max_release_dir = Path(
                tmpdirname, f"max-v2-{config.max_version['name']}"
            )

            shutil.copytree(  ## BaseX databases
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "fixtures", "max"),
                Path(tmp_max_release_dir, "fixtures", "max"),
                Path(cur_dir, ".max", "basex", "data", "max"),
                dirs_exist_ok=True,
            )
            shutil.copytree(
            Path(
                USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "fixtures", "content_html"
            ),
                Path(tmp_max_release_dir, "fixtures", "content_html"),
                Path(cur_dir, "content_html"),
                dirs_exist_ok=True,
            )
            shutil.copytree(
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "fixtures", "templates"),
                Path(tmp_max_release_dir, "fixtures", "templates"),
                Path(cur_dir, "templates"),
                dirs_exist_ok=True,
            )
            shutil.copytree(
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "fixtures", "autoroute"),
                Path(tmp_max_release_dir, "fixtures", "autoroute"),
                Path(cur_dir, "autoroute"),
                dirs_exist_ok=True,
            )

            shutil.copy(
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "fixtures", "config.xml"),
                Path(tmp_max_release_dir, "fixtures", "config.xml"),
                Path(cur_dir, "config.xml"),
            )
        sync()
            _sync_max_instance(cur_dir, verbose=False)

        print("[green]" + _("édition de démonstration installée") + "[/green]")
        print(_("Vous pouvez démarrer MaX avec la commande [bold]climax start[/bold]"))

@@ -559,8 +577,6 @@ def freeze(
    start(WEB_HOST, port_number, http_stop_port=stop_port, service=True)
    # copy website
    try:
        # for lang in config.languages:
        # start_url = f"http://localhost:{port_number}/{lang}/tdm.html"
        start_url = f"http://localhost:{port_number}/"
        geler.freeze(start_url, directory)
    except Exception as e:
@@ -627,7 +643,7 @@ def bundles_add(bundle_name: str):
    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]
    if from_archive is not None:  # todo install from archive
    if from_archive is not None:
        if type(from_archive) is str:
            from_archive = Path(from_archive)
        if not from_archive.is_file():
@@ -771,12 +787,6 @@ def projects():
            config = max_install.config()
            table.add_row(config.title, max_install.path)
    console.print(table)
    # options = []
    # for max_install in climax_db.projects():
    #    options.append(max_install.path)
    # terminal_menu = TerminalMenu(options)
    # menu_entry_index = terminal_menu.show()
    # subprocess.run(["cd", options[menu_entry_index]], shell=True)


# @app.command(help=_("Application web (test)"))
+25 −4
Changes for src/climax/config.py: 25 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -4,6 +4,9 @@ from pathlib import Path
from typing import List, Dict
from requests import get
from functools import cache
import logging

logger = logging.getLogger(__name__)

GITLAB_API_READ_TOKEN = "glpat-5BCYCid1WaxxBgax-7VW"

@@ -31,10 +34,9 @@ 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.2-alpha/max-v2-0.0.2-alpha.zip"

# MAX_DISTRO = "https://git.unicaen.fr/pdn-certic/max-v2/-/archive/0.0.2-alpha/max-v2-0.0.2-alpha.zip"
# CURRENT_MAX_DISTRO_DIR = os.path.splitext(os.path.basename(MAX_DISTRO))[0]

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",
    "linux/x86_64": "https://download.java.net/java/GA/jdk22.0.2/c9ecb94cd31b495da20a27d4581645e8/9/GPL/openjdk-22.0.2_linux-x64_bin.tar.gz",
@@ -52,13 +54,32 @@ def max_releases() -> List[Dict]:
        response = get(
            "https://git.unicaen.fr/api/v4/projects/2429/releases",
            headers={"PRIVATE-TOKEN": GITLAB_API_READ_TOKEN},
            timeout=5,
        )
        if response.ok:
            return json.loads(response.content)
    except:  # noqa: E722
        pass
        logger.warning(
            "Could not fetch MaX releases from Gitlab API, fallback to cached response."
        )

    with open(
        Path(os.path.dirname(os.path.realpath(__file__)), "max_releases.json")
    ) as f:
        return json.load(f)


@cache
def max_release(release_name: str) -> Dict:
    for release in max_releases():
        if release.get("name") == release_name:
            if release["assets"]["count"] > 0:
                for source in release["assets"]["sources"]:
                    if source["format"] == "zip":
                        release["zip_url"] = source["url"]
            return release


@cache
def latest_max_release() -> Dict:
    return max_release(max_releases()[0]["name"])
+2 −1
Changes for src/climax/model.py: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -199,7 +199,8 @@ class MaXProjectConfig:
        conf = self.xml_soup.find("configuration")
        version_node = conf.find("version")
        if not version_node:
            version_node = conf.new_tag("version")
            version_node = self.xml_soup.new_tag("version")
            conf.append(version_node)
        version_node["name"] = values.get("name", "")
        version_node["url"] = values.get("url", "")