@@ -0,0 +1,659 @@
1+// Working-tree snapshots and unified diffs.
2+
3+#include "diff.h"
4+
5+#include <dirent.h>
6+#include <errno.h>
7+#include <fcntl.h>
8+#include <stdbool.h>
9+#include <stdio.h>
10+#include <stdlib.h>
11+#include <string.h>
12+#include <sys/stat.h>
13+#include <unistd.h>
14+
15+#define MAX_FILE_BYTES (1u << 20)
16+#define MAX_TOTAL_BYTES (32u << 20)
17+#define BINARY_SNIFF 8192
18+#define CONTEXT 3
19+#define MAX_TRACE_BYTES (64u << 20)
20+
21+// ---- small helpers --------------------------------------------------------
22+
23+static void *xmalloc(size_t n) {
24+ void *p = malloc(n);
25+ if (!p) abort();
26+ return p;
27+}
28+
29+static void *xcalloc(size_t n, size_t size) {
30+ void *p = calloc(n, size);
31+ if (!p) abort();
32+ return p;
33+}
34+
35+static char *xstrdup(const char *s) {
36+ size_t n = strlen(s) + 1;
37+ char *p = xmalloc(n);
38+ memcpy(p, s, n);
39+ return p;
40+}
41+
42+typedef struct {
43+ char *data;
44+ size_t len;
45+ size_t cap;
46+} buf;
47+
48+static void buf_add(buf *b, const char *p, size_t n) {
49+ if (b->len + n + 1 > b->cap) {
50+ size_t cap = b->cap ? b->cap : 64;
51+ while (cap < b->len + n + 1) cap *= 2;
52+ b->data = realloc(b->data, cap);
53+ if (!b->data) abort();
54+ b->cap = cap;
55+ }
56+ memcpy(b->data + b->len, p, n);
57+ b->len += n;
58+ b->data[b->len] = '\0';
59+}
60+
61+static void buf_addz(buf *b, const char *s) { buf_add(b, s, strlen(s)); }
62+
63+// ---- file states and cache ------------------------------------------------
64+
65+enum { FS_TEXT, FS_BINARY, FS_LARGE, FS_LINK, FS_UNTRACKED };
66+
67+typedef struct {
68+ size_t size;
69+ struct timespec mtime;
70+ ino_t ino;
71+ int kind;
72+ char *content; // NULL unless FS_TEXT
73+ int refs;
74+} file_state;
75+
76+// A captured file. `rel` and `abs` are owned.
77+typedef struct {
78+ char *rel;
79+ char *abs;
80+ size_t size;
81+ struct timespec mtime;
82+ ino_t ino;
83+ bool link;
84+} found;
85+
86+typedef struct {
87+ found *items;
88+ size_t len;
89+ size_t cap;
90+} found_list;
91+
92+static void found_add(found_list *l, char *rel, char *abs, const struct stat *st, bool link) {
93+ if (l->len == l->cap) {
94+ l->cap = l->cap ? l->cap * 2 : 64;
95+ l->items = realloc(l->items, l->cap * sizeof *l->items);
96+ if (!l->items) abort();
97+ }
98+ l->items[l->len++] = (found){
99+ .rel = rel,
100+ .abs = abs,
101+ .size = (size_t)st->st_size,
102+ .mtime = st->st_mtim,
103+ .ino = st->st_ino,
104+ .link = link,
105+ };
106+}
107+
108+static const char *const IGNORED_DIRS[] = {
109+ ".git", ".hg", ".svn", "node_modules", ".venv", "venv",
110+ "__pycache__", ".mypy_cache", ".pytest_cache",
111+};
112+
113+static bool ignored_dir(const char *name) {
114+ for (size_t i = 0; i < sizeof IGNORED_DIRS / sizeof *IGNORED_DIRS; i++)
115+ if (strcmp(name, IGNORED_DIRS[i]) == 0) return true;
116+ return false;
117+}
118+
119+static void walk_dir(const char *dir, const char *relbase, found_list *out) {
120+ DIR *d = opendir(dir);
121+ if (!d) return;
122+ struct dirent *de;
123+ while ((de = readdir(d))) {
124+ if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) continue;
125+
126+ size_t fl = strlen(dir) + strlen(de->d_name) + 2;
127+ char *full = xmalloc(fl);
128+ snprintf(full, fl, "%s/%s", dir, de->d_name);
129+ size_t rl = strlen(relbase) + strlen(de->d_name) + 2;
130+ char *rel = xmalloc(rl);
131+ if (relbase[0]) snprintf(rel, rl, "%s/%s", relbase, de->d_name);
132+ else snprintf(rel, rl, "%s", de->d_name);
133+
134+ struct stat st;
135+ if (lstat(full, &st) == 0) {
136+ if (S_ISDIR(st.st_mode)) {
137+ if (!ignored_dir(de->d_name)) walk_dir(full, rel, out);
138+ } else if (S_ISLNK(st.st_mode)) {
139+ found_add(out, rel, full, &st, true);
140+ rel = NULL;
141+ full = NULL;
142+ } else if (S_ISREG(st.st_mode)) {
143+ found_add(out, rel, full, &st, false);
144+ rel = NULL;
145+ full = NULL;
146+ }
147+ }
148+ free(rel);
149+ free(full);
150+ }
151+ closedir(d);
152+}
153+
154+static bool same_stat(const file_state *s, const found *f) {
155+ return s->size == f->size && s->ino == f->ino &&
156+ s->mtime.tv_sec == f->mtime.tv_sec && s->mtime.tv_nsec == f->mtime.tv_nsec;
157+}
158+
159+static bool mtime_at_or_after(const found *f, const struct timespec *since) {
160+ if (f->mtime.tv_sec != since->tv_sec) return f->mtime.tv_sec > since->tv_sec;
161+ return f->mtime.tv_nsec >= since->tv_nsec;
162+}
163+
164+static file_state *build_state(const found *f, bool over_budget) {
165+ file_state *s = xcalloc(1, sizeof *s);
166+ s->size = f->size;
167+ s->mtime = f->mtime;
168+ s->ino = f->ino;
169+ if (f->link) {
170+ s->kind = FS_LINK;
171+ return s;
172+ }
173+ if (f->size > MAX_FILE_BYTES) {
174+ s->kind = FS_LARGE;
175+ return s;
176+ }
177+ if (over_budget) {
178+ s->kind = FS_UNTRACKED;
179+ return s;
180+ }
181+ int fd = open(f->abs, O_RDONLY);
182+ if (fd < 0) {
183+ s->kind = FS_UNTRACKED;
184+ return s;
185+ }
186+ char *data = xmalloc(f->size + 1);
187+ size_t off = 0;
188+ while (off < f->size) {
189+ ssize_t n = read(fd, data + off, f->size - off);
190+ if (n < 0) {
191+ if (errno == EINTR) continue;
192+ break;
193+ }
194+ if (n == 0) break;
195+ off += (size_t)n;
196+ }
197+ close(fd);
198+ data[off] = '\0';
199+ size_t sniff = off < BINARY_SNIFF ? off : BINARY_SNIFF;
200+ for (size_t i = 0; i < sniff; i++) {
201+ if (data[i] == '\0') {
202+ free(data);
203+ s->kind = FS_BINARY;
204+ return s;
205+ }
206+ }
207+ s->kind = FS_TEXT;
208+ s->content = data;
209+ s->size = off;
210+ return s;
211+}
212+
213+static void release(file_state *s) {
214+ if (--s->refs > 0) return;
215+ free(s->content);
216+ free(s);
217+}
218+
219+typedef struct {
220+ char *path;
221+ file_state *state;
222+} cache_entry;
223+
224+static cache_entry *g_cache;
225+static size_t g_cache_len;
226+
227+static int cmp_cache(const void *a, const void *b) {
228+ const cache_entry *x = a, *y = b;
229+ return strcmp(x->path, y->path);
230+}
231+
232+// The cache is kept sorted by path so lookups stay logarithmic.
233+static file_state *cache_find(const char *path) {
234+ size_t lo = 0, hi = g_cache_len;
235+ while (lo < hi) {
236+ size_t mid = lo + (hi - lo) / 2;
237+ int c = strcmp(path, g_cache[mid].path);
238+ if (c == 0) return g_cache[mid].state;
239+ if (c < 0) hi = mid;
240+ else lo = mid + 1;
241+ }
242+ return NULL;
243+}
244+
245+struct snapshot_entry {
246+ char *path;
247+ file_state *state;
248+};
249+
250+struct cage_snapshot {
251+ struct snapshot_entry *entries;
252+ size_t len;
253+};
254+
255+static int cmp_entry(const void *a, const void *b) {
256+ const struct snapshot_entry *x = a, *y = b;
257+ return strcmp(x->path, y->path);
258+}
259+
260+struct cage_snapshot *cage_snapshot_capture(const struct timespec *force_since) {
261+ found_list files = {0};
262+ char cwd[4096];
263+ if (!getcwd(cwd, sizeof cwd)) strcpy(cwd, ".");
264+ walk_dir(cwd, "", &files);
265+
266+ struct cage_snapshot *snap = xcalloc(1, sizeof *snap);
267+ snap->entries = xmalloc((files.len ? files.len : 1) * sizeof *snap->entries);
268+ cache_entry *new_cache = xmalloc((files.len ? files.len : 1) * sizeof *new_cache);
269+ size_t new_len = 0;
270+ size_t total = 0;
271+
272+ for (size_t i = 0; i < files.len; i++) {
273+ found *f = &files.items[i];
274+ file_state *old = cache_find(f->rel);
275+ bool forced = force_since && mtime_at_or_after(f, force_since);
276+ bool reuse = old && !f->link && !forced && same_stat(old, f);
277+ file_state *s = reuse ? old : build_state(f, total >= MAX_TOTAL_BYTES);
278+
279+ s->refs++; // the new cache holds a reference
280+ new_cache[new_len++] = (cache_entry){.path = xstrdup(f->rel), .state = s};
281+ s->refs++; // the snapshot holds a reference
282+ snap->entries[snap->len++] = (struct snapshot_entry){.path = xstrdup(f->rel), .state = s};
283+ if (s->kind == FS_TEXT) total += s->size;
284+ }
285+
286+ for (size_t i = 0; i < g_cache_len; i++) {
287+ release(g_cache[i].state);
288+ free(g_cache[i].path);
289+ }
290+ free(g_cache);
291+ qsort(new_cache, new_len, sizeof *new_cache, cmp_cache);
292+ g_cache = new_cache;
293+ g_cache_len = new_len;
294+
295+ for (size_t i = 0; i < files.len; i++) {
296+ free(files.items[i].rel);
297+ free(files.items[i].abs);
298+ }
299+ free(files.items);
300+
301+ qsort(snap->entries, snap->len, sizeof *snap->entries, cmp_entry);
302+ return snap;
303+}
304+
305+void cage_snapshot_free(struct cage_snapshot *s) {
306+ if (!s) return;
307+ for (size_t i = 0; i < s->len; i++) {
308+ release(s->entries[i].state);
309+ free(s->entries[i].path);
310+ }
311+ free(s->entries);
312+ free(s);
313+}
314+
315+// ---- unified diff ---------------------------------------------------------
316+
317+typedef struct {
318+ const char *p;
319+ size_t len;
320+ bool nl; // the line ended with a newline
321+} line;
322+
323+static line *split_lines(const char *s, size_t n, size_t *count) {
324+ size_t cap = 16, cnt = 0;
325+ line *ls = xmalloc(cap * sizeof *ls);
326+ size_t i = 0;
327+ while (i < n) {
328+ size_t start = i;
329+ while (i < n && s[i] != '\n') i++;
330+ ls[cnt].p = s + start;
331+ ls[cnt].len = i - start;
332+ ls[cnt].nl = i < n;
333+ if (i < n) i++;
334+ if (++cnt == cap) {
335+ cap *= 2;
336+ ls = realloc(ls, cap * sizeof *ls);
337+ if (!ls) abort();
338+ }
339+ }
340+ *count = cnt;
341+ return ls;
342+}
343+
344+static bool line_eq(const line *a, const line *b) {
345+ return a->len == b->len && memcmp(a->p, b->p, a->len) == 0;
346+}
347+
348+enum { OP_EQ, OP_DEL, OP_INS };
349+
350+typedef struct {
351+ int kind;
352+ line l;
353+} op;
354+
355+// Myers O(ND) diff of two line arrays, producing an edit script in order.
356+static op *myers(const line *a, size_t n, const line *b, size_t m, size_t *out_len) {
357+ if (n == 0 && m == 0) {
358+ *out_len = 0;
359+ return NULL;
360+ }
361+ size_t cap = n + m;
362+ op *ops = xmalloc((cap ? cap : 1) * sizeof *ops);
363+ size_t cnt = 0;
364+
365+ if (n == 0) {
366+ for (size_t i = 0; i < m; i++) ops[cnt++] = (op){OP_INS, b[i]};
367+ *out_len = cnt;
368+ return ops;
369+ }
370+ if (m == 0) {
371+ for (size_t i = 0; i < n; i++) ops[cnt++] = (op){OP_DEL, a[i]};
372+ *out_len = cnt;
373+ return ops;
374+ }
375+
376+ int max = (int)(n + m);
377+ size_t vsize = (size_t)(2 * max + 3);
378+ int offset = max + 1;
379+ int *v = xcalloc(vsize, sizeof *v);
380+ v[offset + 1] = 0;
381+
382+ int **trace = NULL;
383+ size_t trace_len = 0, trace_cap = 0;
384+ size_t trace_bytes = 0;
385+ int found_d = -1;
386+
387+ for (int d = 0; d <= max; d++) {
388+ if (trace_bytes + vsize * sizeof *v > MAX_TRACE_BYTES) break;
389+ if (trace_len == trace_cap) {
390+ trace_cap = trace_cap ? trace_cap * 2 : 16;
391+ trace = realloc(trace, trace_cap * sizeof *trace);
392+ if (!trace) abort();
393+ }
394+ int *snap = xmalloc(vsize * sizeof *snap);
395+ memcpy(snap, v, vsize * sizeof *snap);
396+ trace[trace_len++] = snap;
397+ trace_bytes += vsize * sizeof *snap;
398+
399+ for (int k = -d; k <= d; k += 2) {
400+ int x;
401+ if (k == -d || (k != d && v[k - 1 + offset] < v[k + 1 + offset]))
402+ x = v[k + 1 + offset];
403+ else
404+ x = v[k - 1 + offset] + 1;
405+ int y = x - k;
406+ while (x < (int)n && y < (int)m && line_eq(&a[x], &b[y])) {
407+ x++;
408+ y++;
409+ }
410+ v[k + offset] = x;
411+ if (x >= (int)n && y >= (int)m) {
412+ found_d = d;
413+ break;
414+ }
415+ }
416+ if (found_d >= 0) break;
417+ }
418+
419+ if (found_d < 0) {
420+ // Trace budget exceeded: fall back to a coarse replacement.
421+ for (size_t i = 0; i < n; i++) ops[cnt++] = (op){OP_DEL, a[i]};
422+ for (size_t i = 0; i < m; i++) ops[cnt++] = (op){OP_INS, b[i]};
423+ for (size_t i = 0; i < trace_len; i++) free(trace[i]);
424+ free(trace);
425+ free(v);
426+ *out_len = cnt;
427+ return ops;
428+ }
429+
430+ int x = (int)n, y = (int)m;
431+ for (int d = found_d; d >= 0; d--) {
432+ int *vt = trace[d];
433+ int k = x - y;
434+ int prev_k;
435+ if (k == -d || (k != d && vt[k - 1 + offset] < vt[k + 1 + offset]))
436+ prev_k = k + 1;
437+ else
438+ prev_k = k - 1;
439+ int prev_x = vt[prev_k + offset];
440+ int prev_y = prev_x - prev_k;
441+ while (x > prev_x && y > prev_y) {
442+ ops[cnt++] = (op){OP_EQ, a[x - 1]};
443+ x--;
444+ y--;
445+ }
446+ if (d > 0) {
447+ if (x == prev_x) {
448+ ops[cnt++] = (op){OP_INS, b[y - 1]};
449+ y--;
450+ } else {
451+ ops[cnt++] = (op){OP_DEL, a[x - 1]};
452+ x--;
453+ }
454+ }
455+ }
456+
457+ for (size_t i = 0; i < trace_len; i++) free(trace[i]);
458+ free(trace);
459+ free(v);
460+
461+ for (size_t i = 0, j = cnt - 1; i < j; i++, j--) {
462+ op tmp = ops[i];
463+ ops[i] = ops[j];
464+ ops[j] = tmp;
465+ }
466+ *out_len = cnt;
467+ return ops;
468+}
469+
470+static void add_range(char *dst, size_t cap, size_t start, size_t count) {
471+ if (count == 0) snprintf(dst, cap, "%zu,0", start - 1);
472+ else snprintf(dst, cap, "%zu,%zu", start, count);
473+}
474+
475+static char *unified(const char *path, const char *a, size_t alen,
476+ const char *b, size_t blen) {
477+ size_t na, nb;
478+ line *la = split_lines(a, alen, &na);
479+ line *lb = split_lines(b, blen, &nb);
480+ size_t on;
481+ op *ops = myers(la, na, lb, nb, &on);
482+
483+ size_t *opref = xmalloc((on + 1) * sizeof *opref);
484+ size_t *npref = xmalloc((on + 1) * sizeof *npref);
485+ opref[0] = npref[0] = 0;
486+ for (size_t i = 0; i < on; i++) {
487+ opref[i + 1] = opref[i] + (ops[i].kind == OP_EQ || ops[i].kind == OP_DEL);
488+ npref[i + 1] = npref[i] + (ops[i].kind == OP_EQ || ops[i].kind == OP_INS);
489+ }
490+
491+ buf out = {0};
492+ buf_addz(&out, "Index: ");
493+ buf_addz(&out, path);
494+ buf_addz(&out, "\n===================================================================\n--- ");
495+ buf_addz(&out, path);
496+ buf_addz(&out, "\n+++ ");
497+ buf_addz(&out, path);
498+ buf_addz(&out, "\n");
499+
500+ size_t i = 0;
501+ while (i < on) {
502+ while (i < on && ops[i].kind == OP_EQ) i++;
503+ if (i >= on) break;
504+ size_t block_start = i;
505+ size_t block_end = i;
506+ while (block_end < on && ops[block_end].kind != OP_EQ) block_end++;
507+ size_t last = block_end;
508+ for (;;) {
509+ size_t g = last;
510+ while (g < on && ops[g].kind == OP_EQ) g++;
511+ if (g >= on) break;
512+ if (g - last > 2 * CONTEXT) break;
513+ size_t b2 = g;
514+ while (b2 < on && ops[b2].kind != OP_EQ) b2++;
515+ last = b2;
516+ }
517+ size_t hs = block_start >= CONTEXT ? block_start - CONTEXT : 0;
518+ size_t he = last + CONTEXT <= on ? last + CONTEXT : on;
519+
520+ char r1[32], r2[32], hdr[96];
521+ add_range(r1, sizeof r1, opref[hs] + 1, opref[he] - opref[hs]);
522+ add_range(r2, sizeof r2, npref[hs] + 1, npref[he] - npref[hs]);
523+ snprintf(hdr, sizeof hdr, "@@ -%s +%s @@\n", r1, r2);
524+ buf_addz(&out, hdr);
525+
526+ for (size_t k = hs; k < he; k++) {
527+ char prefix = ops[k].kind == OP_DEL ? '-' : ops[k].kind == OP_INS ? '+' : ' ';
528+ buf_add(&out, &prefix, 1);
529+ buf_add(&out, ops[k].l.p, ops[k].l.len);
530+ buf_addz(&out, "\n");
531+ if (!ops[k].l.nl) buf_addz(&out, "\\ No newline at end of file\n");
532+ }
533+ i = he;
534+ }
535+
536+ free(opref);
537+ free(npref);
538+ free(ops);
539+ free(la);
540+ free(lb);
541+ return out.data;
542+}
543+
544+// ---- diffs between snapshots ----------------------------------------------
545+
546+static const char *note_base(int kind) {
547+ if (kind == FS_BINARY) return "binary file";
548+ if (kind == FS_LARGE) return "large file";
549+ return "file not tracked";
550+}
551+
552+static char *note_text(int kind, const char *verb) {
553+ const char *base = note_base(kind);
554+ char *out = xmalloc(strlen(base) + strlen(verb) + 2);
555+ sprintf(out, "%s %s", base, verb);
556+ return out;
557+}
558+
559+// Fills `*out` and returns true when the file changed; false means no change.
560+static bool diff_one(const char *path, const file_state *before,
561+ const file_state *after, cage_file_diff *out) {
562+ out->path = xstrdup(path);
563+ out->patch = NULL;
564+ out->note = NULL;
565+
566+ if (before == NULL) {
567+ if (after->kind == FS_LINK) {
568+ out->note = xstrdup("symlink created");
569+ } else if (after->content == NULL) {
570+ out->note = note_text(after->kind, "created");
571+ } else {
572+ out->patch = unified(path, "", 0, after->content, after->size);
573+ }
574+ return true;
575+ }
576+ if (after == NULL) {
577+ if (before->kind == FS_LINK) {
578+ out->note = xstrdup("symlink removed");
579+ } else if (before->content == NULL) {
580+ out->note = note_text(before->kind, "deleted");
581+ } else {
582+ out->patch = unified(path, before->content, before->size, "", 0);
583+ }
584+ return true;
585+ }
586+ if (before->kind == FS_LINK || after->kind == FS_LINK) {
587+ if (before->ino == after->ino && before->size == after->size &&
588+ before->mtime.tv_sec == after->mtime.tv_sec &&
589+ before->mtime.tv_nsec == after->mtime.tv_nsec)
590+ return false;
591+ out->note = xstrdup("symlink changed");
592+ return true;
593+ }
594+ if (before->content != NULL && after->content != NULL) {
595+ if (before->size == after->size && memcmp(before->content, after->content, before->size) == 0)
596+ return false;
597+ out->patch = unified(path, before->content, before->size, after->content, after->size);
598+ return true;
599+ }
600+ if (before->size == after->size && before->ino == after->ino &&
601+ before->mtime.tv_sec == after->mtime.tv_sec && before->mtime.tv_nsec == after->mtime.tv_nsec)
602+ return false;
603+ int kind = after->content == NULL ? after->kind : before->kind;
604+ out->note = note_text(kind, "changed");
605+ return true;
606+}
607+
608+cage_file_diff *cage_snapshot_diff(const struct cage_snapshot *before,
609+ const struct cage_snapshot *after, size_t *len) {
610+ cage_file_diff *out = NULL;
611+ size_t cap = 0, n = 0;
612+ size_t i = 0, j = 0;
613+ while (i < before->len || j < after->len) {
614+ const char *path;
615+ int cmp;
616+ if (i >= before->len) cmp = 1;
617+ else if (j >= after->len) cmp = -1;
618+ else cmp = strcmp(before->entries[i].path, after->entries[j].path);
619+
620+ cage_file_diff d;
621+ bool changed;
622+ if (cmp < 0) {
623+ path = before->entries[i].path;
624+ changed = diff_one(path, before->entries[i].state, NULL, &d);
625+ i++;
626+ } else if (cmp > 0) {
627+ path = after->entries[j].path;
628+ changed = diff_one(path, NULL, after->entries[j].state, &d);
629+ j++;
630+ } else {
631+ path = before->entries[i].path;
632+ changed = diff_one(path, before->entries[i].state, after->entries[j].state, &d);
633+ i++;
634+ j++;
635+ }
636+ if (!changed) {
637+ free(d.path);
638+ continue;
639+ }
640+ if (n == cap) {
641+ cap = cap ? cap * 2 : 8;
642+ out = realloc(out, cap * sizeof *out);
643+ if (!out) abort();
644+ }
645+ out[n++] = d;
646+ }
647+ *len = n;
648+ return out;
649+}
650+
651+void cage_file_diffs_free(cage_file_diff *diffs, size_t len) {
652+ if (!diffs) return;
653+ for (size_t i = 0; i < len; i++) {
654+ free(diffs[i].path);
655+ free(diffs[i].patch);
656+ free(diffs[i].note);
657+ }
658+ free(diffs);
659+}