grace/htmlua

HTML Templating Engine

git clone https://git.gae.moe/grace/htmlua

Grace Yoder55a1697

1.0.0-alpha
2.0 KiB59 linesraw
1const std = @import("std");
2const Io = std.Io;
3const File = Io.File;
4const Allocator = std.mem.Allocator;
5const ArenaAllocator = std.heap.ArenaAllocator;
6const ArrayList = std.ArrayList;
7const StringArrayHashMap = std.StringArrayHashMapUnmanaged;
8
9const HTMLua = @import("root.zig");
10
11pub fn main(init: std.process.Init) !void {
12    const io = init.io;
13
14    var arena = std.heap.ArenaAllocator.init(init.gpa);
15    defer arena.deinit();
16    const alloc = arena.allocator();
17
18    var state: HTMLua.Parser = .{
19        .component_resolver = &resolver,
20        .tags = &[_]HTMLua.ParserTag{
21            HTMLua.tags.Include,
22            HTMLua.tags.Export,
23            HTMLua.tags.Use,
24        },
25        .tag_stack = try ArrayList([]const u8).initCapacity(alloc, 256),
26        .exported_parts = try StringArrayHashMap([]const u8).init(alloc, &[0][]const u8{}, &[0][]const u8{}),
27    };
28
29    // I dont like this but this is temporary so its ok
30    const args = try init.minimal.args.toSlice(alloc);
31    const file_path = if (args.len != 1) args[1] else null;
32    const file = if (file_path) |fp|
33        try Io.Dir.cwd().openFile(io, fp, .{ .mode = .read_only })
34    else
35        null;
36    defer if (file) |f| f.close(io);
37
38    const in_buf = try alloc.alloc(u8, 1024);
39    var in =
40        if (file) |f| f.reader(io, in_buf) else File.stdin().reader(io, in_buf);
41
42    const out_buf = try alloc.alloc(u8, 1024);
43    var out = File.stdout().writer(io, out_buf);
44
45    try HTMLua.parseTemplate(&arena, io, &state, &in.interface, &out.interface);
46
47    try out.flush();
48}
49
50// https://ziggit.dev/t/zig-0-15-1-reader-writer-dont-make-copies-of-fieldparentptr-based-interfaces/11719
51fn resolver(arena: *ArenaAllocator, io: Io, path: []const u8) anyerror!*Io.Reader {
52    const read_buff = try arena.allocator().alloc(u8, 1024);
53    const cwd = std.Io.Dir.cwd();
54
55    var file = try cwd.openFile(io, path, .{ .mode = .read_only });
56    const reader = try arena.allocator().create(Io.File.Reader);
57    reader.* = file.reader(io, read_buff);
58    return &reader.interface;
59}