85 lines
2.3 KiB
Python
85 lines
2.3 KiB
Python
import logging
|
|
import shutil
|
|
from pathlib import Path
|
|
import os
|
|
|
|
from .config import SOURCE_DIRECTORY, DIST_DIRECTORY, STATIC_DIRECTORY
|
|
|
|
|
|
logger = logging.getLogger("stsg.build")
|
|
|
|
|
|
def copy_static():
|
|
src = str(Path(SOURCE_DIRECTORY, STATIC_DIRECTORY))
|
|
dst = str(Path(DIST_DIRECTORY, STATIC_DIRECTORY))
|
|
|
|
if not os.path.exists(src):
|
|
logger.warn("The static folder '%s' wasn't defined.", src)
|
|
return
|
|
|
|
logger.info("copying static files from '%s' to '%r'", src, dst)
|
|
|
|
os.makedirs(dst, exist_ok=True)
|
|
|
|
for root, dirs, files in os.walk(src):
|
|
if any(p.startswith(".") for p in Path(root).parts):
|
|
continue
|
|
|
|
# Compute relative path from the source root
|
|
rel_path = os.path.relpath(root, src)
|
|
dest_dir = os.path.join(dst, rel_path)
|
|
|
|
os.makedirs(dest_dir, exist_ok=True)
|
|
|
|
for file in files:
|
|
if file.startswith("."):
|
|
continue
|
|
|
|
src_file = os.path.join(root, file)
|
|
dest_file = os.path.join(dest_dir, file)
|
|
shutil.copy2(src_file, dest_file)
|
|
|
|
|
|
class Context:
|
|
def __init__(self, root: str = SOURCE_DIRECTORY):
|
|
self.file = Path(root, "index.html")
|
|
|
|
current_root = Path(root)
|
|
while current_root.parts and self.file is None:
|
|
current_file = Path(current_root, "index.html")
|
|
if current_file.exists() and current_file.is_file:
|
|
self.file = current_file
|
|
|
|
current_root = current_root.parent
|
|
|
|
if self.file is None:
|
|
logger.error("couldn't find context for %s", root)
|
|
exit(1)
|
|
logger.info("%s found context %r", root, str(self.file))
|
|
|
|
def get_text(self, placeholder_values: dict):
|
|
text = self.file.read_text()
|
|
|
|
for key, value in placeholder_values.items():
|
|
text = text.replace(f"<{key}/>", value)
|
|
text = text.replace(f"<{key} />", value)
|
|
|
|
return text
|
|
|
|
|
|
def build():
|
|
logger.info("building static page")
|
|
copy_static()
|
|
|
|
context = Context()
|
|
|
|
# debug
|
|
t = context.get_text({
|
|
"content": """
|
|
<h1 class="title">Hello World</h1>
|
|
<p class="subtitle">My first website with <strong>Bulma</strong>!</p>
|
|
"""
|
|
})
|
|
with Path(DIST_DIRECTORY, "index.html").open("w") as f:
|
|
f.write(t)
|