aboutsummaryrefslogtreecommitdiff
path: root/converter/src/main.zig
blob: bc60e3501c4ba757f6a3bd89f46560dccbfcd746 (plain)
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
38
39
40
41
const std = @import("std");

pub fn main() !void {
    const a = std.heap.page_allocator;
    const contentdir = try std.fs.cwd().openDir("../content", .{.iterate = true});
    var walker = try contentdir.walk(a);
    while (try walker.next()) |we| {
        if (std.mem.endsWith(u8, we.basename, ".md")) {
            std.log.info("converting file {s}", .{we.basename});
            const file = try we.dir.readFileAlloc(a, we.basename, 1_000_000);
            const start = (std.mem.indexOf(u8, file, "---\n") orelse return error.NoFrontmatter) + 4;
            const end = (std.mem.lastIndexOf(u8, file, "---\n") orelse return error.NoFrontMatter);

            var childproc = std.process.Child.init(&.{"yq", "-o", "json"}, a);
            childproc.stdin_behavior = .Pipe;
            childproc.stdout_behavior = .Pipe;
            childproc.stderr_behavior = .Pipe;
            std.log.info("spawn", .{});
            try childproc.spawn();
            std.log.info("writeAll", .{});
            try childproc.stdin.?.writeAll(file[start..end]);
            childproc.stdin.?.close();
            childproc.stdin = null;

            var stdout = std.ArrayList(u8).init(a);
            var stderr = std.ArrayList(u8).init(a);
            std.log.info("collectOutput", .{});
            try childproc.collectOutput(&stdout, &stderr, 1_000_000);
            std.log.info("got output {s}", .{stdout.items});
            std.log.info("wait", .{});
            const term = try childproc.wait();
            if (term.Exited != 0) {
                return error.ProcessError;
            }
            const fm_json = try stdout.toOwnedSlice();
            const newfile = try std.mem.concat(a, u8, &.{"---\n", fm_json, file[end..]});
            try we.dir.writeFile(we.basename, newfile);
        }
    }
    std.log.info("done!", .{});
}