stempl

Simple template language written in python

git clone git://git.janzachar.dev/stempl.git


0#!/usr/bin/env python3
1import sys
2from pathlib import Path
3import yaml
4
5from context import Context
6from page import Page
7
8
9def process_file(target: Path):
10    ...
11
12def load_global(target: Path) -> Optional[Context]:
13    ctx = Context() 
14    
15    path = target / "global.yml"
16    if not path.is_file():
17        print(f"{target}: no such file 'global.yml'")
18        return
19
20    with open(path) as fp:
21        yml = yaml.safe_load(fp)
22        if yml is not None:
23            ctx.data.update(yml)
24    
25    for key in ("pages", "tags"):
26        if key in ctx:
27            print(f"{target}: '{key}' not allowed in global.yml!")
28            return
29
30    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            return
34        if type(ctx[key]) is not str:
35            print(f"{target}: '{key}' should be a string!")
36            return
37
38    for key in ("src", "build", "templ", "assets"):
39        if not Path(ctx[key]).is_absolute():
40            ctx[key] = target / ctx[key]
41
42    return ctx
43
44def build_tree(root: Path, ctx, pagelist: list):
45    if not root.is_dir():
46        if root.suffix not in (".md", ".html",):
47            return None
48
49        p = Page(root, ctx)
50        pagelist.append(p)
51        return p.ctx
52
53    out = {}
54    for i in root.iterdir():
55        t = build_tree(i, ctx, pagelist)
56        if t is not None:
57            out[i.name] = t
58
59    return out
60
61def build_context(target: Path):
62    ctx = Context()
63    ctx["site"] = load_global(target)
64    if ctx is None:
65        return 1
66
67    pagelist = []
68    ctx["site"]["pages"] = Context()
69    ctx["site"]["pages"].data = build_tree(ctx["site"]["src"], ctx, pagelist)
70
71    for p in pagelist:
72        if "permalink" in p.ctx:
73            continue
74        p.ctx["permalink"] = ctx["site"]["host"] + str(p.path.relative_to(ctx["site"]["src"]))
75
76    for i in pagelist:
77        print("Running", p.path)
78        out = p.run()
79
80        outpath = p.ctx["permalink"]
81        outpath = outpath[len(ctx["site"]["host"]):]
82        outpath = ctx["site"]["build"] / outpath
83        
84        outpath.parent.mkdir(parents=True, exist_ok=True)
85        with open(outpath, "w") as fp:
86            fp.write(out)
87
88
89def process_dir(target: Path):
90    ctx = build_context(target)
91    ...
92
93
94if len(sys.argv) < 2:
95    print("No target provided...")
96    exit(1)
97
98for 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!")
106
107