about summary refs log tree commit diff
path: root/src/rub/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'src/rub/__init__.py')
-rw-r--r--src/rub/__init__.py48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/rub/__init__.py b/src/rub/__init__.py
new file mode 100644
index 0000000..dd963e8
--- /dev/null
+++ b/src/rub/__init__.py
@@ -0,0 +1,48 @@
+# Package initialization
+# Copyright (C) 2022  Nguyễn Gia Phong
+#
+# This file is part of rub.
+#
+# Rub is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Rub is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with rub.  If not, see <https://www.gnu.org/licenses/>.
+
+from os import walk
+from os.path import join
+from pathlib import Path
+from shutil import copytree, rmtree
+
+from jinja2 import Environment
+from markdown_it import MarkdownIt
+from mdit_py_plugins.footnote import footnote_plugin
+
+__all__ = ['glob_files', 'markdown', 'replace']
+md = MarkdownIt('gfm-like').use(footnote_plugin)
+jinja = Environment()
+
+
+def glob_files(root: Path, suffix: str = '') -> list[Path]:
+    """Return the list of all files in given directory, recursively."""
+    return [Path(path)/file for path, dirs, files in walk(root)
+            for file in files if file.endswith(suffix)]
+
+
+def markdown(source: Path, destination: Path) -> None:
+    """Convert source Markdown to destination HTML segment."""
+    template = jinja.from_string(source.read_text())
+    destination.write_text(md.render(template.render()))
+
+
+def replace(source: Path, destination: Path) -> None:
+    """Replace destination with source directory."""
+    rmtree(destination, ignore_errors=True)
+    copytree(source, destination, dirs_exist_ok=True)