79113
Ma
mini-coding-agent / files
mini-coding-agent / src / tui / diff_view.zig
2.5 KB
1const std = @import("std"); 2const styles = @import("styles.zig"); 3const tools = @import("../tools.zig"); 4const highlight = @import("highlight.zig"); 5const render = @import("render.zig"); 6 7const BodyLine = render.BodyLine; 8 9pub const Rendered = struct { 10 lines: []const BodyLine = &.{}, 11 added: usize = 0, 12 removed: usize = 0, 13}; 14 15fn diffHunk() styles.Style { 16 return styles.roles.prompt; 17} 18 19fn diffNote() styles.Style { 20 return styles.roles.comment; 21} 22 23pub fn diffLines(a: std.mem.Allocator, lines: []const []const u8, max_diff_lines: usize) Rendered { 24 if (lines.len > max_diff_lines) { 25 var warn: std.ArrayList(BodyLine) = .empty; 26 warn.append(a, .{ 27 .text = "Diff too large to render efficiently. Full contents in session.jsonl", 28 .style = diffNote(), 29 }) catch {}; 30 return .{ .lines = warn.items }; 31 } 32 var out: std.ArrayList(BodyLine) = .empty; 33 var added: usize = 0; 34 var removed: usize = 0; 35 var in_hunk = false; 36 for (lines) |line| { 37 if (std.mem.startsWith(u8, line, "diff ")) in_hunk = false; 38 const kind = highlight.diffKind(line, in_hunk); 39 if (kind == .hunk) in_hunk = true; 40 const text = render.stripAnsi(a, line); 41 switch (kind) { 42 .hunk => out.append(a, .{ .text = text, .style = diffHunk() }) catch {}, 43 .note => out.append(a, .{ .text = text, .style = diffNote() }) catch {}, 44 .ctx => out.append(a, .{ .text = text, .style = diffNote() }) catch {}, 45 .add, .del => { 46 const is_add = kind == .add; 47 if (is_add) added += 1 else removed += 1; 48 const style = if (is_add) styles.roles.diff_add else styles.roles.diff_delete; 49 out.append(a, .{ .text = text, .style = style }) catch {}; 50 }, 51 } 52 } 53 return .{ .lines = out.items, .added = added, .removed = removed }; 54} 55 56pub fn diffBody(a: std.mem.Allocator, d: tools.FileDiff, max_diff_lines: usize) Rendered { 57 if (d.patch) |patch| { 58 const trimmed = std.mem.trimEnd(u8, patch, " \t\r\n"); 59 var it = std.mem.splitScalar(u8, trimmed, '\n'); 60 var body: std.ArrayList([]const u8) = .empty; 61 while (it.next()) |l| body.append(a, l) catch {}; 62 return diffLines(a, body.items, max_diff_lines); 63 } 64 var out: std.ArrayList(BodyLine) = .empty; 65 if (d.note) |note| out.append(a, .{ .text = note, .style = styles.roles.comment }) catch {}; 66 return .{ .lines = out.items }; 67}