xonecas.io
79113
Ma

mini-coding-agent / files

mini-coding-agent / src / tools / snapshot.zig

6.8 KB
1const std = @import("std");
2const platform = @import("../platform.zig");
3const filesystem = @import("../filesystem.zig");
4const text = @import("../text.zig");
5const diff = @import("../diff.zig");
6const gitignore = @import("../gitignore.zig");
7const tools = @import("../tools.zig");
8
9const max_file_bytes = 1 << 20;
10const max_total_bytes = 32 << 20;
11const max_ignore_bytes = 1 << 20;
12
13const Kind = enum { text, binary, large, link, untracked };
14
15const FileState = struct {
16    size: u64,
17    mtime: i128,
18    inode: u64,
19    kind: Kind,
20    content: ?[]const u8,
21};
22
23pub const Tree = std.StringHashMap(FileState);
24
25pub const Ignore = struct {
26    root: []const u8 = "",
27    dirs: []const []const u8 = &.{},
28    uses_gitignore: bool = true,
29};
30
31pub fn capture(a: std.mem.Allocator, ignore: Ignore) !Tree {
32    var tree = Tree.init(a);
33
34    var arena = std.heap.ArenaAllocator.init(a);
35    defer arena.deinit();
36    const tmp = arena.allocator();
37
38    var matcher = gitignore.Matcher.init(tmp);
39    if (ignore.dirs.len > 0) try matcher.pushPatterns("", ignore.dirs);
40    if (ignore.uses_gitignore) {
41        if (filesystem.readFileAlloc(tmp, ".gitignore", max_ignore_bytes)) |content| {
42            try matcher.pushFile("", content);
43        } else |_| {}
44    }
45
46    var stack: std.ArrayList([]const u8) = .empty;
47    try stack.append(tmp, ignore.root);
48
49    var total: u64 = 0;
50    while (stack.pop()) |dir_rel| {
51        const open_path = if (dir_rel.len == 0) "." else dir_rel;
52        var d = std.Io.Dir.cwd().openDir(platform.io, open_path, .{ .iterate = true }) catch continue;
53        defer d.close(platform.io);
54
55        var it = d.iterate();
56        while (it.next(platform.io) catch null) |entry| {
57            const rel = if (dir_rel.len == 0)
58                try a.dupe(u8, entry.name)
59            else
60                try std.fmt.allocPrint(a, "{s}/{s}", .{ dir_rel, entry.name });
61
62            const is_dir = entry.kind == .directory;
63            if (matcher.check(rel, is_dir)) |ig| {
64                if (ig) continue;
65            }
66
67            if (is_dir) {
68                if (ignore.uses_gitignore) {
69                    const gi = try std.fmt.allocPrint(tmp, "{s}/.gitignore", .{rel});
70                    if (filesystem.readFileAlloc(tmp, gi, max_ignore_bytes)) |content| {
71                        try matcher.pushFile(rel, content);
72                    } else |_| {}
73                }
74                try stack.append(tmp, rel);
75                continue;
76            }
77
78            const st = std.Io.Dir.cwd().statFile(platform.io, rel, .{ .follow_symlinks = false }) catch {
79                continue;
80            };
81            var state = FileState{
82                .size = st.size,
83                .mtime = st.mtime.nanoseconds,
84                .inode = st.inode,
85                .kind = .untracked,
86                .content = null,
87            };
88            if (st.kind == .sym_link) {
89                state.kind = .link;
90            } else if (st.kind != .file) {
91                continue;
92            } else if (st.size > max_file_bytes) {
93                state.kind = .large;
94            } else if (total >= max_total_bytes) {
95                state.kind = .untracked;
96            } else {
97                const buf = std.Io.Dir.cwd().readFileAlloc(platform.io, rel, a, .limited(max_file_bytes + 1)) catch {
98                    state.kind = .untracked;
99                    try tree.put(rel, state);
100                    continue;
101                };
102                if (text.isBinary(buf)) {
103                    state.kind = .binary;
104                } else {
105                    state.kind = .text;
106                    state.content = buf;
107                    total += st.size;
108                }
109            }
110            try tree.put(rel, state);
111        }
112    }
113    return tree;
114}
115
116fn sameStat(x: FileState, y: FileState) bool {
117    return x.size == y.size and x.mtime == y.mtime and x.inode == y.inode;
118}
119
120fn noteFor(a: std.mem.Allocator, kind: Kind, verb: []const u8) []const u8 {
121    return switch (kind) {
122        .binary => std.fmt.allocPrint(a, "binary file {s}", .{verb}) catch "binary file changed",
123        .large => std.fmt.allocPrint(a, "large file {s}", .{verb}) catch "large file changed",
124        else => std.fmt.allocPrint(a, "file not tracked ({s})", .{verb}) catch "file not tracked",
125    };
126}
127
128fn diffOne(a: std.mem.Allocator, path: []const u8, before: ?FileState, after: ?FileState) !?tools.FileDiff {
129    if (before == null) {
130        const af = after.?;
131        if (af.kind == .link) return .{ .path = path, .note = "symlink created" };
132        if (af.content == null) return .{ .path = path, .note = noteFor(a, af.kind, "created") };
133        return .{ .path = path, .patch = try diff.unified(a, "", af.content.?) };
134    }
135    if (after == null) {
136        const bf = before.?;
137        if (bf.kind == .link) return .{ .path = path, .note = "symlink removed" };
138        if (bf.content == null) return .{ .path = path, .note = noteFor(a, bf.kind, "deleted") };
139        return .{ .path = path, .patch = try diff.unified(a, bf.content.?, "") };
140    }
141    const bf = before.?;
142    const af = after.?;
143    if (bf.kind == .link or af.kind == .link) {
144        return if (sameStat(bf, af)) null else .{ .path = path, .note = "symlink changed" };
145    }
146    if (bf.content != null and af.content != null) {
147        if (std.mem.eql(u8, bf.content.?, af.content.?)) return null;
148        return .{ .path = path, .patch = try diff.unified(a, bf.content.?, af.content.?) };
149    }
150    if (sameStat(bf, af)) return null;
151    return .{ .path = path, .note = noteFor(a, if (af.content == null) af.kind else bf.kind, "changed") };
152}
153
154pub fn diffText(a: std.mem.Allocator, diffs: []const tools.FileDiff) ![]const u8 {
155    var out: std.Io.Writer.Allocating = .init(a);
156    const w = &out.writer;
157    for (diffs) |d| {
158        if (d.patch) |patch| {
159            if (patch.len == 0) continue;
160            try w.print("--- {s}\n", .{d.path});
161            try w.writeAll(patch);
162            if (patch[patch.len - 1] != '\n') try w.writeByte('\n');
163        } else if (d.note) |note| {
164            try w.print("--- {s}: {s}\n", .{ d.path, note });
165        }
166    }
167    return out.written();
168}
169
170pub fn diffTrees(a: std.mem.Allocator, before: Tree, after: Tree) ![]tools.FileDiff {
171    var paths: std.ArrayList([]const u8) = .empty;
172    var it = before.iterator();
173    while (it.next()) |e| try paths.append(a, e.key_ptr.*);
174    var it2 = after.iterator();
175    while (it2.next()) |e| {
176        if (!before.contains(e.key_ptr.*)) try paths.append(a, e.key_ptr.*);
177    }
178    std.mem.sort([]const u8, paths.items, {}, struct {
179        fn lt(_: void, x: []const u8, y: []const u8) bool {
180            return std.mem.lessThan(u8, x, y);
181        }
182    }.lt);
183
184    var out: std.ArrayList(tools.FileDiff) = .empty;
185    for (paths.items) |p| {
186        if (try diffOne(a, p, before.get(p), after.get(p))) |d| try out.append(a, d);
187    }
188    return out.toOwnedSlice(a);
189}