Skip to content
This repository has been archived by the owner on Dec 2, 2024. It is now read-only.

Commit

Permalink
PluginManager for managing plugins registed by the user to generate c…
Browse files Browse the repository at this point in the history
…ustom Transifex configurations.
  • Loading branch information
why-not-try-calmer committed Dec 22, 2022
1 parent 42d0609 commit 8e6b855
Show file tree
Hide file tree
Showing 6 changed files with 148 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pytransifex/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import logging

logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.INFO)
56 changes: 56 additions & 0 deletions pytransifex/config-plugins/opengis-mkdocs/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# © 2022 Mario Baranzini @ [email protected]
import glob
import logging
import os
from typing import NamedTuple

import frontmatter


class TxProjectConfig(NamedTuple):
TX_ORGANIZATION = "opengisch"
TX_PROJECT = "qfield-documentation"
TX_SOURCE_LANG = "en"
TX_TYPE = "GITHUBMARKDOWN"


def create_transifex_config(config: TxProjectConfig):
"""Parse all source documentation files and add the ones with tx_slug metadata
defined to transifex config file.
"""
logging.info("Start creating transifex configuration")

current_dir = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(current_dir, "..", ".tx", "config")
root = os.path.join(current_dir, "..")
count = 0

with open(config_file, "w") as f:
f.write("[main]\n")
f.write("host = https://www.transifex.com\n\n")

for file in glob.iglob(
current_dir + "/../documentation/**/*.en.md", recursive=True
):

# Get relative path of file
relative_path = os.path.relpath(file, start=root)

tx_slug = frontmatter.load(file).get("tx_slug", None)

if tx_slug:
logging.info(
f"Found file with tx_slug defined: {relative_path}, {tx_slug}"
)
f.write(
f"[o:{config.TX_ORGANIZATION}:p:{config.TX_PROJECT}:r:{tx_slug}]\n"
)
f.write(
f"file_filter = {''.join(relative_path.split('.')[:-2])}.<lang>.md\n"
)
f.write(f"source_file = {relative_path}\n")
f.write(f"source_lang = {config.TX_SOURCE_LANG}\n")
f.write(f"type = {config.TX_TYPE}\n\n")
count += 1

logging.info(f"Transifex configuration created. {count} resources added.")
1 change: 1 addition & 0 deletions pytransifex/config-plugins/opengis-mkdocs/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-frontmatter==1.0.0
2 changes: 1 addition & 1 deletion pytransifex/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,4 @@ def get_or_default(k: str, obj: dict[str, Any]) -> Any:
truthy_obj = {k: v for k, v in obj.items() if v}
if k in truthy_obj:
return truthy_obj[k]
return defaults[k]
return defaults[k]
73 changes: 73 additions & 0 deletions pytransifex/plugins_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import sys
from functools import reduce
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from typing import Any


class PluginManager:
# list of path_to_ subdir, path_to_ main.py
discovered_subdir_main: list[tuple[Path, Path]] = []
# successfully imported modules
imported_modules: dict[str, Any] = {}

@staticmethod
def discover():
"""
Expecting directory structure:
pytransifex/
config-plugins/{plugins}
main.py
"""
plugins_dir = Path.cwd().joinpath("pytransifex", "config-plugins")
subdirs = [f for f in plugins_dir.iterdir() if f.is_dir()]

def collect_mains(acc: list[Path], sub: Path):
main = Path(sub).joinpath("main.py")

if main.exists() and main.is_file():
acc.append(main)

return acc

collected = reduce(collect_mains, subdirs, [])
PluginManager.discovered_subdir_main = list(zip(subdirs, collected))

@staticmethod
def load_plugin(target_plugin_dir: str):
conventional_main = "main.py"

if name_main := next(
(
(main_p, directory_p.name)
for directory_p, main_p in PluginManager.discovered_subdir_main
if directory_p.name == target_plugin_dir
), None
):
main, name = name_main

if name in PluginManager.imported_modules:
print("Already imported! Nothing to do.")
return

if spec := spec_from_file_location(conventional_main, main):
module = module_from_spec(spec)
sys.modules[conventional_main] = module

if spec.loader:
spec.loader.exec_module(module)
PluginManager.imported_modules[name] = module
print(
f"Successfully imported and loaded {module}! Imported modules read: {PluginManager.imported_modules}"
)

else:
raise Exception(f"Failed to load module '{module}' at {main}")

else:
raise Exception(f"Unable to find spec 'main.py' for {main}")

else:
raise Exception(
f"Couldn't find the '{target_plugin_dir}' directory; it was expected to be a child of the 'pytransifex' directory."
)
16 changes: 16 additions & 0 deletions tests/test_config-plugins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import unittest

from pytransifex.plugins_manager import PluginManager


class TestPluginsRegistrar(unittest.TestCase):
def test1_plugin_discover(self):
PluginManager.discover()
assert list(PluginManager.discovered_subdir_main)

def test2_plugin_import(self):
PluginManager.load_plugin("opengis-mkdocs")
assert list(PluginManager.imported_modules)

def test3_imported_plugin(self):
assert PluginManager.imported_modules["opengis-mkdocs"].TxProjectConfig

0 comments on commit 8e6b855

Please sign in to comment.