summaryrefslogtreecommitdiff
path: root/tools/reload_edit.zig
blob: 0fe2bf32ee1ccae78b2d4acf0238597dfe889c04 (plain) (blame)
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
42
43
44
45
46
47
48
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);
}