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

update new config

parent 473c6612
Loading
Loading
Loading
Loading
+175 −49
Changes for src/climax/__main__.py: 175 added lines, 49 removed lines.
Original line number Diff line number Diff line
@@ -13,6 +13,8 @@ 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
@@ -23,9 +25,23 @@ gettext.textdomain("messages")
_ = gettext.gettext


USER_DIR = os.getenv("CLIMAX_HOME") or Path(Path.home(), ".climax")
USER_DIR.mkdir(exist_ok=True)
CACHE_DIR = Path(USER_DIR, "cache")
WELCOME_PAGE = """
<h1>Bienvenue dans MaX !</h1>
<p>
    Vous pouvez personnaliser cette page en éditant le fichier content_html/fr/index.html
</p>
<p>
    Retrouvez la documentation de MaX à l'adresse suivante: 
    <a href="https://pdn-certic.pages.unicaen.fr/max-documentation/">
        https://pdn-certic.pages.unicaen.fr/max-documentation/
    </a>
</p>
"""

USER_MAX_DIR = os.getenv("CLIMAX_HOME") or Path(Path.home(), ".climax")
USER_MAX_DIR = Path(USER_MAX_DIR)
USER_MAX_DIR.mkdir(exist_ok=True)
CACHE_DIR = Path(USER_MAX_DIR, "cache")
CACHE_DIR.mkdir(exist_ok=True)
MAX_CONFIG_FILE = "config.xml"
BASEX_DISTRO = "https://files.basex.org/releases/11.1/BaseX111.zip"
@@ -35,13 +51,6 @@ SAXON_DISTRO = (

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 = {
@@ -54,16 +63,19 @@ 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-dumb-tei">
    <title>untitled</title>
<configuration xmlns="http://certic.unicaen.fr/max/ns/1.0" env="dev" vocabulary-bundle="max-dumb-xml">
    <languages>
        <language>fr</language>
        <language>en</language>
    </languages>
    <title>mon Corpus Numérique</title>
    <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"/>
        <bundle name="max-dumb-xml"/>
        <bundle name="max-export"/>
        <bundle name="max-dev"/>
    </bundles>
</configuration>"""
</configuration>
"""


def _free_port() -> int:
@@ -91,10 +103,56 @@ class MaXProjectConfig:
        if not conf:
            conf = self.xml_soup.new_tag("configuration")
            conf["env"] = "dev"
            conf["vocabulary-bundle"] = "max-dumb-tei"
            conf["vocabulary-bundle"] = "max-dumb-xml"
            conf["xmlns"] = "http://certic.unicaen.fr/max/ns/1.0"
            self.xml_soup.append(conf)

    @property
    def available_bundles(self) -> Dict[str, Dict]:
        active_bundles = self.bundles
        available_bundles = {}
        available_bundles_xml = Path(
            os.path.dirname(self.config_file_path),
            ".max",
            "resources",
            "available-bundles.xml",
        )
        if available_bundles_xml.is_file():
            with open(available_bundles_xml, "r") as file_handle:
                soup = BeautifulSoup(file_handle.read(), "xml")
                for b in soup.find_all("bundle"):
                    available_bundles[b["name"]] = {
                        "name": b["name"],
                        "url": b["url"] if b.has_attr("url") else "",
                        "description": b["description"]
                        if b.has_attr("description")
                        else "",
                        "active": b["name"] in active_bundles.keys(),
                        "vocabulary": True
                        if (
                            b.has_attr("vocabulary-bundle")
                            and b["vocabulary-bundle"] == "true"
                        )
                        else False,
                    }
        return available_bundles

    @property
    def max_version(self) -> str:
        expath_pkg = Path(
            os.path.dirname(self.config_file_path),
            ".max",
            "resources",
            "expath-pkg.xml",
        )
        if expath_pkg.is_file():
            with open(expath_pkg, "r") as expath_handle:
                soup = BeautifulSoup(expath_handle.read(), "xml")
                package = soup.find("package")
                if package:
                    return package["version"]
        return ""

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

    @vocabulary_bundle.setter
@@ -159,13 +217,16 @@ class MaXProjectConfig:
            nodes.append(language_tag)

    @property
    def bundles(self) -> Dict[str, str]:
    def bundles(self) -> Dict[str, Dict]:
        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"]
                vals[bundle["name"]] = {
                    "name": bundle["name"],
                    "url": bundle["url"] if bundle.has_attr("url") else "",
                }
        return vals

    @bundles.setter
@@ -293,9 +354,9 @@ def ensure_java() -> Path:
        cur_sys = current_system()
        suitable_jdk = find_jdk(cur_sys)
        if suitable_jdk:
            destination_folder = Path(USER_DIR, "jdk")
            destination_folder = Path(USER_MAX_DIR, "jdk")
            if not destination_folder.exists():
                destination_archive = Path(USER_DIR, os.path.basename(suitable_jdk))
                destination_archive = Path(USER_MAX_DIR, os.path.basename(suitable_jdk))
                cached_download(suitable_jdk, destination_archive)
                unzip(destination_archive, destination_folder)
            if cur_sys in ["linux/x86_64", "linux/amd64"]:
@@ -322,9 +383,9 @@ def ensure_java() -> Path:


def ensure_max_distro() -> Path:
    destination_folder = Path(USER_DIR, "max")
    destination_folder = Path(USER_MAX_DIR, "max")
    if not destination_folder.exists():
        destination_archive = Path(USER_DIR, "max.zip")
        destination_archive = Path(USER_MAX_DIR, "max.zip")
        cached_download(MAX_DISTRO, destination_archive)
        unzip(destination_archive, destination_folder)
    return destination_folder
@@ -362,20 +423,20 @@ def _sync_bundles(root_directory: Path):
            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():
    for bundle_name, bundle 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)
            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))
            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"):
def _install_new_max_instance(root_directory: Path):
    print(
        "[bold]"
        + _("Initialisation d'une nouvelle instance de MaX dans {}").format(
@@ -399,23 +460,28 @@ def _install_new_max_instance(root_directory: Path, vocabulary: str = "TEI"):
        f.write(".max\n")

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

    new_max_config = MaXProjectConfig(config_file_path)
    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()
    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)

    _sync_bundles(root_directory)

    Path(root_directory, "content_html", "fr").mkdir(exist_ok=True, parents=True)
    welcome_page = Path(root_directory, "content_html", "fr", "index.html")
    with open(welcome_page, "w") as f:
        f.write(WELCOME_PAGE)

    print(
        "[bold]"
        + _("La nouvelle instance de MaX est prête dans {}").format(root_directory)
@@ -428,7 +494,8 @@ def _install_new_max_instance(root_directory: Path, vocabulary: str = "TEI"):
    )


def _sync_max_instance(root_directory: Path):
def _sync_max_instance(root_directory: Path, verbose=True):
    if verbose:
        print(
            "[bold]"
            + _("Initialisation de l'instance de MaX existant dans {}").format(
@@ -449,16 +516,21 @@ def _sync_max_instance(root_directory: Path):
        cached_download(SAXON_DISTRO, saxon_zip_destination)

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

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

    _sync_bundles(root_directory)
    if verbose:
        print(
            "[bold]"
            + _("L'instance de MaX est prête dans {}").format(root_directory)
@@ -492,7 +564,6 @@ def new(
    directory: Annotated[
        Optional[Path], typer.Argument(help=_("chemin vers un dossier"))
    ] = os.getcwd(),
    vocabulary: str = "TEI",
):
    ensure_java()
    ensure_max_distro()
@@ -501,7 +572,7 @@ def new(
        print(_("Le dossier contient une instance de MaX. Utiliser la commande init"))
        raise typer.Exit()
    else:
        _install_new_max_instance(root_directory, vocabulary)
        _install_new_max_instance(root_directory)


@app.command(
@@ -515,30 +586,32 @@ def demo():
        cur_dir = os.getcwd()

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

        shutil.copy(
            Path(USER_DIR, "max", CURRENT_MAX_DISTRO_DIR, "fixtures", "config.xml"),
            Path(USER_MAX_DIR, "max", CURRENT_MAX_DISTRO_DIR, "fixtures", "config.xml"),
            Path(cur_dir, "config.xml"),
        )

        shutil.copy(
            Path(
                USER_DIR,
                USER_MAX_DIR,
                "max",
                CURRENT_MAX_DISTRO_DIR,
                "src",
@@ -554,7 +627,7 @@ def demo():

        shutil.copy(
            Path(
                USER_DIR,
                USER_MAX_DIR,
                "max",
                CURRENT_MAX_DISTRO_DIR,
                "src",
@@ -631,11 +704,15 @@ def cache_clear():
    for p in CACHE_DIR.iterdir():
        if p.is_file():
            p.unlink(missing_ok=True)
    shutil.rmtree(Path(USER_MAX_DIR, "max"), ignore_errors=True)


@app.command(help=_("Affiche la configuration de MaX"))
def config():
    check_cwd_is_max()
    config = max_config()
    print(f"MaX version: {config.max_version}\n")
    print("Project configuration:\n")
    print(max_config())


@@ -687,6 +764,55 @@ def bundles_remove(bundle_name: str):
            keep_bundles[active_bundle_name] = active_bundle_url
    config.bundles = keep_bundles
    config.write()
    bundles_list_available()


@app.command(help=_("Liste les bundles disponibles"))
def bundles_list_available():
    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(
            "[bold]{}[/bold]".format(bundle["name"]),
            "[green]{}[/green]".format(_("oui"))
            if bundle["active"]
            else "[red]{}[/red]".format(_("non")),
            bundle["description"],
            "[green]{}[/green]".format(_("oui"))
            if bundle["vocabulary"]
            else "[red]{}[/red]".format(_("non")),
        )
    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):
    check_cwd_is_max()
    config = max_config()
    current_bundles_config = config.bundles
    if from_archive is not None:
        pass  # todo: install from archive
    else:
        if bundle_name not in config.available_bundles.keys():
            print(_("[red]{} n'est pas un bundle disponible[red]").format(bundle_name))
            raise typer.Exit(code=1)
        else:
            for (
                available_bundle_name,
                available_bundle,
            ) in config.available_bundles.items():
                if available_bundle_name == bundle_name:
                    if available_bundle["vocabulary"]:
                        config.vocabulary_bundle = bundle_name
                    current_bundles_config[bundle_name] = available_bundle["url"]
                    config.bundles = current_bundles_config
                    config.write()
                    _sync_max_instance(os.getcwd(), verbose=False)
                    bundles_list_available()


get_yolk()