robin/maivi

a tiny cute lua web framework

git clone https://git.robinwobin.dev/robin/maivi

robinmaivi: proper io usage6e07b35

push-srxvuswpkqxx
1.9 KiB72 linesraw
1const std = @import("std");
2const Io = std.Io;
3
4const zlua = @import("zlua");
5pub const Lua = zlua.Lua;
6
7const maivi = @import("../root.zig");
8const helpers = maivi.helpers;
9
10/// * Pops from Stack: `0`
11/// * Pushes to Stack: `1`
12pub fn read(l: *Lua, io: Io, path: []const u8) !void {
13    const dir = try Io.Dir.openDirAbsolute(io, maivi.config.root, .{});
14    defer dir.close(io);
15    const contents = try helpers.read_file(io, maivi.allocator, dir, path);
16    defer maivi.allocator.free(contents);
17
18    var ctx: Context = .{
19        .path = path,
20        .content = contents,
21    };
22    try maivi.lua.trigger(l, Context, &ctx, .read_data, .{
23        .path = path,
24        .pattern = path,
25    });
26
27    if (ctx.content_ref) |ref| {
28        _ = l.getIndexRaw(zlua.registry_index, ref);
29    } else _ = l.pushString(contents);
30}
31
32const Context = struct {
33    path: []const u8,
34    content: []const u8,
35    content_ref: ?i32 = null,
36    ref: ?i32 = null, // reusable lua ref for hooks
37
38    pub fn toLua(self: Context, l: *Lua) !void {
39        // { url = ..., path = ..., content = ... }
40        l.createTable(0, 2);
41
42        // path
43        _ = l.pushString(self.path);
44        l.setField(-2, "path"); // path
45
46        // content
47        _ = l.pushString(self.content);
48        l.setField(-2, "content"); // content
49
50        // metatable
51        try maivi.lua.setMethodTable(l, MT);
52    }
53
54    pub const MT = struct {
55        pub fn use(l: *Lua) !i32 {
56            l.argCheck(l.isTable(1), 1, "ctx");
57            l.argCheck(l.isString(2), 2, "string");
58            // -1 => content, -2 => ctx
59
60            const ctx = blk: {
61                const ltype_ptr = l.getField(1, "ptr");
62                defer l.pop(1);
63                if (ltype_ptr != .light_userdata) return error.InvalidPtr;
64                break :blk try l.toUserdata(Context, -1);
65            };
66
67            ctx.content_ref = maivi.lua.toRef(l, -1);
68
69            return 0;
70        }
71    };
72};