//! Copies a source tree and applies textual edits to the copy, for //! `addReloadCheck`: `reload_edit [ ]...`. //! 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); }