diff options
Diffstat (limited to 'tools/patch.zig')
| -rw-r--r-- | tools/patch.zig | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/tools/patch.zig b/tools/patch.zig new file mode 100644 index 00000000..a72624ff --- /dev/null +++ b/tools/patch.zig @@ -0,0 +1,39 @@ +//! One upstream file patched at make time, for build/patches.zig: +//! `patch <in> <out> [--append <file>] [<count> <old> <new>]...`. +//! Each `old` must occur exactly `count` times, and every occurrence is +//! replaced by `new`, in order; then `file` follows after an empty line. +//! An `old` that moved or doubled writes nothing and fails the step. +const std = @import("std"); + +pub fn main(init: std.process.Init) !void { + const io = init.io; + const arena = init.arena.allocator(); + var args = init.minimal.args.iterate(); + _ = args.skip(); + const in_path = args.next() orelse return error.Usage; + const out_path = args.next() orelse return error.Usage; + const cwd = std.Io.Dir.cwd(); + + var source = try cwd.readFileAlloc(io, in_path, arena, .limited(4 << 20)); + var append: []const u8 = ""; + var failed = false; + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--append")) { + append = try cwd.readFileAlloc(io, args.next() orelse return error.Usage, arena, .limited(1 << 20)); + continue; + } + const count = try std.fmt.parseInt(usize, arg, 10); + const old = args.next() orelse return error.Usage; + const new = args.next() orelse return error.Usage; + const found = std.mem.count(u8, source, old); + if (found != count) { + std.log.err("{s} changed: the text to replace occurs {d} times, not {d} (redo its patch in build/patches.zig):\n{s}", .{ in_path, found, count, old }); + failed = true; + continue; + } + source = try std.mem.replaceOwned(u8, arena, source, old, new); + } + if (failed) std.process.exit(1); + const out = if (append.len == 0) source else try std.mem.concat(arena, u8, &.{ source, "\n", append }); + try cwd.writeFile(io, .{ .sub_path = out_path, .data = out }); +} |
