From 1be03893434272e4413eaf15dee68b99c42ebf6d Mon Sep 17 00:00:00 2001 From: ochafik Date: Sat, 13 Apr 2024 18:39:22 +0100 Subject: [PATCH] build: don't call xxd from build.zig --- build.zig | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/build.zig b/build.zig index 3e33d24bd..0fcc674a7 100644 --- a/build.zig +++ b/build.zig @@ -142,7 +142,43 @@ pub fn build(b: *std.build.Builder) !void { const server_assets = [_][]const u8{ "index.html", "index.js", "completion.js", "json-schema-to-grammar.mjs" }; for (server_assets) |asset| { - const gen_hpp = b.addSystemCommand(&.{ "bash", "-c", b.fmt("cd examples/server/public && xxd -i {s} ../{s}.hpp", .{ asset, asset }) }); - server.step.dependOn(&gen_hpp.step); + const input_path = b.fmt("examples/server/public/{s}", .{asset}); + const output_path = b.fmt("examples/server/{s}.hpp", .{asset}); + + const input_file = try std.fs.cwd().openFile(input_path, .{}); + defer input_file.close(); + const input = try input_file.readToEndAlloc(b.allocator, std.math.maxInt(usize)); + defer b.allocator.free(input); + + const hex = try b.allocator.alloc(u8, input.len * 6); + defer b.allocator.free(hex); + var i: usize = 0; + for (input) |byte| { + const high = byte >> 4; + const low = byte & 0xF; + hex[i] = '0'; + hex[i + 1] = 'x'; + hex[i + 2] = if (high < 10) high + '0' else high - 10 + 'A'; + hex[i + 3] = if (low < 10) low + '0' else low - 10 + 'A'; + hex[i + 4] = ','; + hex[i + 5] = ' '; + i += 6; + } + + const output_file = try std.fs.cwd().createFile(output_path, .{}); + defer output_file.close(); + + const name = try b.allocator.alloc(u8, asset.len); + defer b.allocator.free(name); + std.mem.copy(u8, name, asset); + std.mem.replaceScalar(u8, name, '-', '_'); + std.mem.replaceScalar(u8, name, '.', '_'); + + try output_file.writeAll(b.fmt( + "unsigned char {s}[] = {{{s}}};\nunsigned int {s}_len = {d};\n", + .{ name, hex, name, input.len }, + )); + + std.debug.print("Dumped hex of \"{s}\" ({s}) to {s}\n", .{ input_path, name, output_path }); } }