sapp

Suckless awk preprocessor
Log | Files | Refs | README | LICENSE

sapp (992B)


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
#!/usr/bin/awk -f

function q(s) {
    gsub(/{%%/, "{%", s);
    gsub(/\\/, "\\\\", s);
    gsub(/%/, "%%", s);
    gsub(/'\''/, "'\''\"'\''\"'\''", s);
    return s;
}

content == 0 && /^$/ { content = 1; next; }
content == 0 && /^\w+:/ {
    key = substr($0, 0, index($0, ":") - 1)
    value = substr($0, index($0, ":") + 1)
    gsub(/^\s+/, "", key); gsub(/\s+$/, "", key);
    gsub(/^\s+/, "", value); gsub(/\s+$/, "", value);
    page[key] = value;
}
content == 1 { body = body "{%nl%}" $0; }

END {
    for (i in page)
        print("export page_" i "='\''" q(page[i]) "'\'';");

    n = split(body, g, /{%[^%]+%}/, sep);

    for (i = 1; i < n; i++) {
        if (g[i] != "")
            printf("printf -- '\''%s'\'';", q(g[i]));
        gsub(/^{%\s*/, "", sep[i]); gsub(/\s*%}$/, "", sep[i]);
        if (sep[i] == "nl")
            print("echo;");
        else if (sep[i] in page)
            printf("printf -- '\''%s'\'';", q(page[sep[i]]));
        else print(sep[i] ";");
    }
}