diff options
Diffstat (limited to 'tools/reload_edit.zig')
| -rw-r--r-- | tools/reload_edit.zig | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/tools/reload_edit.zig b/tools/reload_edit.zig new file mode 100644 index 0000000..0fe2bf3 --- /dev/null +++ b/tools/reload_edit.zig @@ -0,0 +1,49 @@ +//! Copies a source tree and applies textual edits to the copy, for +//! `addReloadCheck`: `reload_edit <in dir> <out dir> [<file> <old> <new>]...`. +//! Each `old` must occur exactly once in its file (relative to the tree), +//! or nothing is written and the edit is reported. +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 input = try cwd.openDir(io, in_path, .{ .iterate = true }); + defer input.close(io); + var output = try cwd.createDirPathOpen(io, out_path, .{}); + defer output.close(io); + + var walker = try input.walk(arena); + defer walker.deinit(); + while (try walker.next(io)) |entry| switch (entry.kind) { + .directory => try output.createDirPath(io, entry.path), + .file, .sym_link => try input.copyFile(entry.path, output, entry.path, io, .{}), + else => {}, + }; + + var failed = false; + while (args.next()) |file| { + const old = args.next() orelse return error.Usage; + const new = args.next() orelse return error.Usage; + const source = output.readFileAlloc(io, file, arena, .limited(64 << 20)) catch |err| { + std.log.err("edit {s}: {t}", .{ file, err }); + failed = true; + continue; + }; + const count = std.mem.count(u8, source, old); + if (count != 1) { + std.log.err("edit {s}: the text to replace occurs {d} times, not once:\n{s}", .{ file, count, old }); + failed = true; + continue; + } + const at = std.mem.indexOf(u8, source, old).?; + const edited = try std.mem.concat(arena, u8, &.{ source[0..at], new, source[at + old.len ..] }); + try output.writeFile(io, .{ .sub_path = file, .data = edited }); + } + if (failed) std.process.exit(1); +} |
