Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232const std = @import("std");const tools = @import("../tools.zig");const schema = @import("schema.zig");
pub const definition = .{ .name = "edit", .description = \\Replace text in an existing file. Each edit replaces old with new. old must \\match the file exactly, including whitespace, and occur exactly once; do not \\include the LINE| prefix of read output. Every edit matches the file as it was \\before the call, so edits must not overlap. Nothing is written when any edit \\fails. , .Args = Args, .execute = execute,};
pub const Edit = struct { old: schema.String(.{ .description = "Exact text to replace; it must occur once in the file.", .min_length = 1 }), new: schema.String(.{ .description = "Replacement text." }),};
pub const Args = struct { path: schema.String(.{ .description = "File path, relative to the working directory or absolute." }), edits: schema.Array(Edit, .{ .description = "Edits to apply, in any order.", .min_items = 1 }),};
pub const Output = struct { /// The text the model sees. text: []const u8, /// The edits in file order. hunks: []const Hunk,};
pub const Hunk = struct { /// 1-based line of the edit in the file before the call. line: usize, old: []const u8, new: []const u8,};
pub fn execute(ctx: tools.Context, arena: std.mem.Allocator, args: Args) !Output { const path = args.path.value; const edits = args.edits.items; const data = std.Io.Dir.cwd().readFileAlloc(ctx.io, path, arena, .limited(tools.max_file_bytes)) catch |err| return tools.pathError(ctx, arena, path, err);
const starts = try arena.alloc(usize, edits.len); for (edits, starts, 1..) |edit, *start, number| { const old = edit.old.value; start.* = std.mem.indexOf(u8, data, old) orelse return fail(ctx, arena, "edit {d}: old was not found in the file", .{number}); if (std.mem.indexOfPos(u8, data, start.* + 1, old) != null) { return fail(ctx, arena, "edit {d}: old occurs more than once in the file; include more of the surrounding text", .{number}); } }
const order = try arena.alloc(usize, edits.len); for (order, 0..) |*slot, index| { slot.* = index; } std.mem.sort(usize, order, starts, struct { fn lower(list: []const usize, a: usize, b: usize) bool { return list[a] < list[b]; } }.lower); var size = data.len; for (order, 0..) |index, rank| { if (rank > 0) { const before = order[rank - 1]; if (starts[before] + edits[before].old.value.len > starts[index]) { return fail(ctx, arena, "edits {d} and {d} overlap", .{ @min(before, index) + 1, @max(before, index) + 1 }); } } size = size - edits[index].old.value.len + edits[index].new.value.len; }
var content: std.ArrayList(u8) = try .initCapacity(arena, size); const hunks = try arena.alloc(Hunk, edits.len); var cursor: usize = 0; var line: usize = 1; for (order, hunks) |index, *hunk| { const edit = edits[index]; const at = starts[index]; line += std.mem.countScalar(u8, data[cursor..at], '\n'); hunk.* = .{ .line = line, .old = edit.old.value, .new = edit.new.value }; content.appendSliceAssumeCapacity(data[cursor..at]); content.appendSliceAssumeCapacity(edit.new.value); cursor = at + edit.old.value.len; line += std.mem.countScalar(u8, edit.old.value, '\n'); } content.appendSliceAssumeCapacity(data[cursor..]);
tools.replaceFile(ctx.io, arena, std.Io.Dir.cwd(), path, content.items) catch |err| return tools.pathError(ctx, arena, path, err); return .{ .text = try std.fmt.allocPrint(arena, "edited {s}: {d} edit(s)", .{ path, edits.len }), .hunks = hunks, };}
fn fail(ctx: tools.Context, arena: std.mem.Allocator, comptime fmt: []const u8, args: anytype) error{InvalidEdit} { if (ctx.detail) |slot| { slot.* = std.fmt.allocPrint(arena, fmt, args) catch null; } return error.InvalidEdit;}
const testing = std.testing;
test "edit replaces text that occurs once" { var dir = try tools.TestDir.init(); defer dir.deinit(); const path = try dir.write("f.txt", "hello world");
const edits = &.{.{ .old = "world", .new = "there" }}; const result = dir.call("edit", .{ .path = path, .edits = edits }); try testing.expect(!result.is_error); try testing.expectEqualStrings(try std.fmt.allocPrint(dir.arena(), "edited {s}: 1 edit(s)", .{path}), result.text); try testing.expectEqualStrings("hello there", try dir.read("f.txt"));}
test "the expanded edit result shows each edit by line number as removed and added lines" { var dir = try tools.TestDir.init(); defer dir.deinit(); const path = try dir.write("f.txt", "one\ntwo\r\nthree\n");
const edits = &.{ .{ .old = "three\n", .new = "3" }, .{ .old = "two\r\n", .new = "2\r\n2b\r\n" }, }; const result = dir.call("edit", .{ .path = path, .edits = edits }); try testing.expect(!result.is_error); try testing.expectEqualStrings( "line 2\n-two\n+2\n+2b\nline 3\n-three\n+3", try tools.content.plain(dir.arena(), result.expanded), );}
test "edits match the original file, so two edits can swap text" { var dir = try tools.TestDir.init(); defer dir.deinit(); const path = try dir.write("f.txt", "abcdef");
const edits = &.{ .{ .old = "ab", .new = "cd" }, .{ .old = "cd", .new = "ab" }, }; const result = dir.call("edit", .{ .path = path, .edits = edits }); try testing.expect(!result.is_error); try testing.expectEqualStrings("cdabef", try dir.read("f.txt"));}
test "edit rejects old text that is missing or occurs more than once and writes nothing" { var dir = try tools.TestDir.init(); defer dir.deinit(); const path = try dir.write("f.txt", "aaa b");
const cases = [_]struct { []const u8, []const u8 }{ .{ "c", "edit 2: old was not found in the file" }, .{ "aa", "edit 2: old occurs more than once in the file; include more of the surrounding text" }, }; for (cases) |case| { const edits = &.{ .{ .old = "b", .new = "x" }, .{ .old = case[0], .new = "x" } }; const result = dir.call("edit", .{ .path = path, .edits = edits }); try testing.expect(result.is_error); try testing.expectEqualStrings(case[1], result.text); } try testing.expectEqualStrings("aaa b", try dir.read("f.txt"));}
test "edit rejects overlapping edits" { var dir = try tools.TestDir.init(); defer dir.deinit(); const path = try dir.write("f.txt", "abcdef");
const pairs = [_][2][]const u8{ .{ "cdef", "abcd" }, .{ "abc", "ab" } }; for (pairs) |pair| { const edits = &.{ .{ .old = pair[0], .new = "x" }, .{ .old = pair[1], .new = "y" } }; const result = dir.call("edit", .{ .path = path, .edits = edits }); try testing.expect(result.is_error); try testing.expectEqualStrings("edits 1 and 2 overlap", result.text); } try testing.expectEqualStrings("abcdef", try dir.read("f.txt"));}
test "edit and write name the path they cannot open" { var dir = try tools.TestDir.init(); defer dir.deinit(); const missing = try dir.path("missing.txt"); const under_file = try dir.path("f.txt/a.txt"); _ = try dir.write("f.txt", "x");
const edits = &.{.{ .old = "x", .new = "y" }}; const edited = dir.call("edit", .{ .path = missing, .edits = edits }); try testing.expectEqualStrings(try std.fmt.allocPrint(dir.arena(), "{s}: FileNotFound", .{missing}), edited.text); const written = dir.call("write", .{ .path = under_file, .content = "x" }); try testing.expect(written.is_error); try testing.expectStringStartsWith(written.text, try std.fmt.allocPrint(dir.arena(), "{s}: ", .{under_file}));}
/// The edited path and how many edits it makes.pub fn renderCall(arena: std.mem.Allocator, args: Args) std.mem.Allocator.Error!tools.content.Content { const line = try std.fmt.allocPrint(arena, "{s} ({d} edit(s))", .{ args.path.value, args.edits.items.len }); return tools.content.callLine(arena, definition.name, line);}
const red = 1;const green = 2;
/// Once expanded, each edit as its line number, the removed lines and the added lines.pub fn renderResult(arena: std.mem.Allocator, output: Output) std.mem.Allocator.Error!tools.Rendered { var spans: std.ArrayList(tools.content.Span) = .empty; for (output.hunks) |hunk| { const separator = if (spans.items.len == 0) "" else "\n"; const header = try std.fmt.allocPrint(arena, "{s}line {d}", .{ separator, hunk.line }); try spans.append(arena, .{ .text = header, .style = .{ .bold = true } }); try appendLines(arena, &spans, "\n-", hunk.old, red); try appendLines(arena, &spans, "\n+", hunk.new, green); } return .{ .expanded = spans.items };}
fn appendLines(arena: std.mem.Allocator, spans: *std.ArrayList(tools.content.Span), prefix: []const u8, text: []const u8, color: u8) std.mem.Allocator.Error!void { if (text.len == 0) { return; } var lines = std.mem.splitScalar(u8, std.mem.cutSuffix(u8, text, "\n") orelse text, '\n'); while (lines.next()) |line| { const shown = try std.mem.concat(arena, u8, &.{ prefix, std.mem.trimEnd(u8, line, "\r") }); try spans.append(arena, .{ .text = shown, .style = .{ .color = color } }); }}