Simple template language written in python
git clone git://git.janzachar.dev/stempl.git
0#!/usr/bin/env python31import sys2from pathlib import Path3import yaml45from context import Context6from page import Page789def process_file(target: Path):10 ...1112def load_global(target: Path) -> Optional[Context]:13 ctx = Context()1415 path = target / "global.yml"16 if not path.is_file():17 print(f"{target}: no such file 'global.yml'")18 return1920 with open(path) as fp:21 yml = yaml.safe_load(fp)22 if yml is not None:23 ctx.data.update(yml)2425 for key in ("pages", "tags"):26 if key in ctx:27 print(f"{target}: '{key}' not allowed in global.yml!")28 return2930 for key in ("host", "src", "build", "templ", "assets"):31 if key not in ctx:32 print(f"{target}: '{key}' is mandatory in global.yml!")33 return34 if type(ctx[key]) is not str:35 print(f"{target}: '{key}' should be a string!")36 return3738 for key in ("src", "build", "templ", "assets"):39 if not Path(ctx[key]).is_absolute():40 ctx[key] = target / ctx[key]4142 return ctx4344def build_tree(root: Path, ctx, pagelist: list):45 if not root.is_dir():46 if root.suffix not in (".md", ".html",):47 return None4849 p = Page(root, ctx)50 pagelist.append(p)51 return p.ctx5253 out = {}54 for i in root.iterdir():55 t = build_tree(i, ctx, pagelist)56 if t is not None:57 out[i.name] = t5859 return out6061def build_context(target: Path):62 ctx = Context()63 ctx["site"] = load_global(target)64 if ctx is None:65 return 16667 pagelist = []68 ctx["site"]["pages"] = Context()69 ctx["site"]["pages"].data = build_tree(ctx["site"]["src"], ctx, pagelist)7071 for p in pagelist:72 if "permalink" in p.ctx:73 continue74 p.ctx["permalink"] = ctx["site"]["host"] + str(p.path.relative_to(ctx["site"]["src"]))7576 for i in pagelist:77 print("Running", p.path)78 out = p.run()7980 outpath = p.ctx["permalink"]81 outpath = outpath[len(ctx["site"]["host"]):]82 outpath = ctx["site"]["build"] / outpath8384 outpath.parent.mkdir(parents=True, exist_ok=True)85 with open(outpath, "w") as fp:86 fp.write(out)878889def process_dir(target: Path):90 ctx = build_context(target)91 ...929394if len(sys.argv) < 2:95 print("No target provided...")96 exit(1)9798for target in sys.argv[1:]:99 target = Path(target)100 if target.is_file():101 process_file(target)102 elif target.is_dir():103 process_dir(target)104 else:105 print(f"{target}: invalid path!")106107