about summary refs log tree commit diff
path: root/src/rub/__init__.py
blob: dd963e81c63b1667d3abb6a83f0e290b7b94b060 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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)