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

add tests and config class

parent 80e2f11d
Loading
Loading
Loading
Loading
+2
Changes for pyproject.toml: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -9,6 +9,8 @@ dependencies = [
    "typer>=0.12.3",
    "pyinstaller>=6.9.0",
    "requests>=2.32.3",
    "basexclient>=8.4.4",
    "beautifulsoup4>=4.12.3",
]
readme = "README.md"
requires-python = ">= 3.12"
+194 −85
Changes for src/climax/__main__.py: 194 added lines, 85 removed lines.
Original line number Diff line number Diff line
import subprocess
from http.client import HTTP_PORT
from pathlib import Path
from typing import Optional, Union
from typing_extensions import Annotated
import gettext
from bs4 import BeautifulSoup

locales_dir = Path(__file__).parent / "locales"
gettext.bindtextdomain("messages", str(locales_dir))
@@ -14,7 +14,6 @@ import requests
import os
import stat
import hashlib
import json
import platform
import typer
from rich import print
@@ -26,7 +25,7 @@ USER_DIR = os.getenv("CLIMAX_HOME") or 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"
MAX_CONFIG_FILE = "config.xml"
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"
@@ -38,8 +37,105 @@ JAVA_DISTROS = {
    "windows/amd64": "https://download.java.net/java/GA/jdk22.0.2/c9ecb94cd31b495da20a27d4581645e8/9/GPL/openjdk-22.0.2_windows-x64_bin.zip",
}
WEB_PORT = 8080
WEB_HOST = "localhost"
BASEX_PORT = 1984
DEFAULT_XML_FORMAT = "TEI"
STOP_PORT = 8081
CONFIG_INIT_TEMPLATE = """<configuration env="dev" vocabulary-bundle="max-tei-bundle">
    <title>untitled</title>
    <languages>
        <language>fr</language>
        <language>en</language>
    </languages>
</configuration>"""


class MaXProjectConfig:
    def __init__(self, path_to_config_file: Union[str, Path]):
        self.config_file_path = Path(path_to_config_file).resolve()
        if os.path.isfile(self.config_file_path):
            with open(self.config_file_path, "r") as f:
                self.xml_soup = BeautifulSoup(f, "html.parser")
        else:
            self.xml_soup = BeautifulSoup(CONFIG_INIT_TEMPLATE, "html.parser")
        first = self.xml_soup.find()
        if first and first.name != "configuration":
            raise ValueError(f"{self.config_file_path} is not a MaX configuration file")
        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"
            self.xml_soup.append(conf)

    @property
    def env(self) -> str:
        conf = self.xml_soup.find("configuration")
        val = conf.get("env", "dev")
        return str(val)

    @env.setter
    def env(self, value: str):
        conf = self.xml_soup.find("configuration")
        conf["env"] = value

    @property
    def vocabulary_bundle(self) -> str:
        conf = self.xml_soup.find("configuration")
        val = conf.get("vocabulary-bundle", "max-tei-bundle")
        return str(val)

    @vocabulary_bundle.setter
    def vocabulary_bundle(self, value):
        conf = self.xml_soup.find("configuration")
        conf["vocabulary-bundle"] = value

    @property
    def title(self) -> str:
        val = "untitled"
        conf = self.xml_soup.find("configuration")
        xml_node = conf.find("title")
        if xml_node:
            val = xml_node.text.strip()
        return str(val)

    @title.setter
    def title(self, value):
        conf = self.xml_soup.find("configuration")
        xml_node = conf.find("title")
        if not xml_node:
            xml_node = self.xml_soup.new_tag("title")
            conf.append(xml_node)
        xml_node.string = value

    @property
    def languages(self) -> list[str]:
        vals = []
        conf = self.xml_soup.find("configuration")
        nodes = conf.find("languages")
        if nodes:
            for language in nodes.find_all("language"):
                vals.append(language.text.strip())
        return vals

    @languages.setter
    def languages(self, languages: list[str]):
        conf = self.xml_soup.find("configuration")
        nodes = conf.find("languages")
        if not nodes:
            nodes = self.xml_soup.new_tag("languages")
            conf.append(nodes)
        nodes.clear()
        for language in languages:
            l = self.xml_soup.new_tag("language")
            l.string = language
            nodes.append(l)

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

    def write(self):
        with open(self.config_file_path, "w") as f:
            f.write(str(self))


@lru_cache()
@@ -47,6 +143,28 @@ def current_system() -> str:
    return f"{platform.system()}/{platform.machine()}".lower()


@lru_cache
def class_path_separator() -> str:
    separator = ":"
    current_os = current_system().split("/")[0]
    if current_os == "windows":
        separator = ";"
    return separator


@lru_cache
def cp_paths() -> str:
    basex_dir_path = Path(os.getcwd(), ".max", "basex")
    paths = class_path_separator().join(
        [
            str(Path(basex_dir_path, "BaseX.jar")),
            str(Path(basex_dir_path, "lib", "custom", "*")),
            str(Path(basex_dir_path, "lib", "*")),
        ]
    )
    return paths


@lru_cache()
def find_jdk(cur_sys: str = None) -> Optional[str]:
    if not cur_sys:
@@ -54,33 +172,27 @@ def find_jdk(cur_sys: str = None) -> Optional[str]:
    return JAVA_DISTROS.get(cur_sys, None)


def fetch_config_file() -> Path:
    climax_config_file = Path(os.getcwd(), CLIMAX_CONFIG_FILE)
    if not climax_config_file.exists():
def dir_is_max(directory: Path = None) -> bool:
    if directory is None:
        directory = os.getcwd()
    directory = Path(directory)
    config_file = Path(directory, "config.xml")
    max_dir = Path(directory, ".max")
    if not config_file.exists() or not max_dir.is_dir():
        return False
    return True


def check_cwd_is_max():
    if not dir_is_max():
        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 ?"
                )
            )
            "[red]{}[/red]".format(_("Le dossier n'est pas une installation 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
def max_config() -> MaXProjectConfig:
    return MaXProjectConfig(Path(os.getcwd(), MAX_CONFIG_FILE))


def unzip(source: Union[Path, str], destination: Union[Path, str]) -> bool:
@@ -148,7 +260,7 @@ def ensure_java() -> Path:
    return java_bin


def ensure_max() -> Path:
def ensure_max_distro() -> Path:
    destination_folder = Path(USER_DIR, "max")
    if not destination_folder.exists():
        destination_archive = Path(USER_DIR, "max.zip")
@@ -173,21 +285,21 @@ def ensure_new_max_directory(directory: Optional[Path]) -> Path:
    return directory


app = typer.Typer(help="pouet pouet")
app = typer.Typer(
    help=_("Utilitaire en ligne de commande pour la gestion des projets MaX")
)


@app.command(help=_("Initialisation d'une instance de MaX"))
def init(
    directory: Annotated[
        Optional[Path], typer.Argument(help=_("chemin vers un dossier"))
    ] = os.getcwd(),
    xml_format: str = typer.Option(DEFAULT_XML_FORMAT, help=_("vocabulaire XML")),
    http_port: int = typer.Option(WEB_PORT, help=_("port du serveur web")),
    basex_port: int = typer.Option(BASEX_PORT, help=_("port du serveur basex")),
    ] = os.getcwd()
):
    root_directory = ensure_new_max_directory(directory)
    java_bin = ensure_java()
    max_path = ensure_max()
    ensure_java()
    ensure_max_distro()

    print(
        "[bold]"
        + _("Initialisation d'une instance de MaX dans {}").format(root_directory)
@@ -207,17 +319,6 @@ def init(
        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,
        "java_bin": java_bin,
        "xml_format": xml_format,
    }
    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")
@@ -258,10 +359,10 @@ def init(
    help=_("Installe une édition de démonstration dans l'instance de MaX en cours")
)
def demo():
    check_cwd_is_max()
    if typer.confirm(
        _("Voulez-vous installer une édition de démonstration ?"), default=False
    ):
        config = read_climax_config()
        cur_dir = os.getcwd()
        shutil.copytree(
            Path(USER_DIR, "max", "fixtures", "max"),
@@ -284,63 +385,71 @@ def demo():
        print(_("Vous pouvez démarrer MaX avec la commande [bold]climax run[/bold]"))


@app.command(help=_("Démarre l'instance de MaX du dossier en cours"))
def run():
    class_path_separator = ":"
    current_os = current_system().split("/")[0]
    if current_os == "windows":
        class_path_separator = ";"
    climax_config = read_climax_config()
@app.command(help=_("Arrête l'instance de MaX du dossier en cours"))
def stop(http_stop_port: int = STOP_PORT):
    check_cwd_is_max()
    java_bin_path = ensure_java()
    basex_dir_path = Path(os.getcwd(), ".max", "basex")
    cp_paths = class_path_separator.join(
        [
            str(Path(basex_dir_path, "BaseX.jar")),
            str(Path(basex_dir_path, "lib", "custom", "*")),
            str(Path(basex_dir_path, "lib", "*")),
    process_args = [
        str(java_bin_path),
        "-cp",
        cp_paths(),
        "-Xmx2g",
        "org.basex.BaseXHTTP",
        f"-s{http_stop_port}",
        "stop",
    ]
    subprocess.run(process_args)


@app.command(help=_("Démarre l'instance de MaX du dossier en cours"))
def start(
    http_host: str = WEB_HOST,
    http_port: int = WEB_PORT,
    basex_port: int = BASEX_PORT,
    http_stop_port: int = STOP_PORT,
    service: Annotated[
        bool,
        typer.Option(
            help=_(
                'Démarrer MaX en tant que service. Utiliser "climax stop" pour arrêter le service.'
            )
        ),
    ] = False,
):
    check_cwd_is_max()
    java_bin_path = ensure_java()
    process_args = [
        str(java_bin_path),
        "-cp",
        cp_paths,
        cp_paths(),
        "-Xmx2g",
        "org.basex.BaseXHTTP",
        f"-h{climax_config.get('http_port', HTTP_PORT)}",
        f"-p{basex_port}",
        f"-h{http_port}",
        f"-n{http_host}",
    ]
    print("[green]" + _("Démarrage de MaX...") + "[/green]")
    print(f"java path: {java_bin_path}")
    if service:
        process_args.append("-S")
        process_args.append(f"-s{http_stop_port}")
    print(
        "[green]"
        + _("Démarrage de MaX sur http://{}:{}").format(http_host, http_port)
        + "[/green]"
    )
    subprocess.run(process_args)


@app.command(help=_("Efface le cache de climax"))
def clear_cache():
def cache_clear():
    for p in CACHE_DIR.iterdir():
        if p.is_file():
            p.unlink(missing_ok=True)


@app.command(help=_("Affiche la configuration pour l'instance de MaX en cours"))
def getconfig():
    config = read_climax_config()
    print(config)


@app.command(help=_("Modifie la configuration de l'instance de MaX en cours"))
def setconfig(key: str, value):
    try:
        config = read_climax_config()
        if key == "http_port":
            config[key] = int(value)
        write_climax_config(config)
    except ValueError:
        print(
            "[red]"
            + _("Erreur: valeur {} impossible pour la clef {}").format(
                f"[bold]{value}[/bold]", f"[bold]{key}[/bold]"
            )
            + "[/red]"
        )
@app.command(help=_("Affiche la configuration de MaX"))
def config():
    check_cwd_is_max()
    print(max_config())


if __name__ == "__main__":
+39
Changes for tests.py: 39 added lines, 0 removed lines.
Original line number Diff line number Diff line
import unittest
from src.climax.__main__ import MaXProjectConfig
from pathlib import Path
TEST_CONFIG_FILE = "tests_assets/max_config.xml"
TEST_CONFIG_EMPTY_FILE = "tests_assets/empty_max_config.xml"
TEST_CONFIG_FILE_BAD_ROOT = "tests_assets/bad_root_max_config.xml"


class TestConfigFiles(unittest.TestCase):
    def setUp(self):
        pass

    def test_config(self):
        config = MaXProjectConfig(TEST_CONFIG_FILE)
        self.assertEqual(Path(TEST_CONFIG_FILE).resolve(), config.config_file_path)
        self.assertEqual(["fr", "en"], config.languages)
        self.assertEqual("mon Corpus Numérique", config.title)
        self.assertEqual("dev", config.env)
        self.assertEqual("max-tei-bundle", config.vocabulary_bundle)
        config.title = "new test title"
        self.assertEqual("new test title", config.title)

    def test_empty_config(self):
        config = MaXProjectConfig(TEST_CONFIG_EMPTY_FILE)
        config.title = "empty test title"
        self.assertEqual("empty test title", config.title)

    def test_bad_config(self):
        with self.assertRaises(ValueError) as context:
            MaXProjectConfig(TEST_CONFIG_FILE_BAD_ROOT)

    def test_set_languages(self):
        config = MaXProjectConfig("nothere")
        config.languages = ["fr", "en", "es", "jp"]
        self.assertEqual(["fr", "en", "es", "jp"], config.languages)


if __name__ == '__main__':
    unittest.main()
+1
Changes for tests_assets/bad_root_max_config.xml: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
<notyourtag></notyourtag>
 No newline at end of file

Empty file added.

Loading