Repository navigation
Expand file tree
/
Copy pathgit.zig
More file actions
2879 lines (2643 loc) · 122 KB
/
Copy pathgit.zig
File metadata and controls
2879 lines (2643 loc) · 122 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const string = []const u8;
const time = @import("time");
const extras = @import("extras");
const tracer = @import("tracer");
const nfs = @import("nfs");
const nio = @import("nio");
const root = @import("root"); // temp
pub const Id = *const [40]u8;
pub const TreeId = struct {
id: Id,
pub const zero: TreeId = .{ .id = "0000000000000000000000000000000000000000" };
pub const empty: TreeId = .{ .id = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" }; // echo -n | git hash-object -t tree --stdin
pub fn eql(self: TreeId, other: TreeId) bool {
return std.mem.eql(u8, self.id, other.id);
}
};
pub const CommitId = struct {
id: Id,
pub const zero: CommitId = .{ .id = "0000000000000000000000000000000000000000" };
pub fn eql(self: CommitId, other: CommitId) bool {
return std.mem.eql(u8, self.id, other.id);
}
};
pub const BlobId = struct {
id: Id,
pub const zero: BlobId = .{ .id = "0000000000000000000000000000000000000000" };
pub const empty: BlobId = .{ .id = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" }; // echo -n | git hash-object -t blob --stdin
pub fn eql(self: BlobId, other: BlobId) bool {
return std.mem.eql(u8, self.id, other.id);
}
};
pub const TagId = struct {
id: Id,
pub const zero: BlobId = .{ .id = "0000000000000000000000000000000000000000" };
pub fn eql(self: TagId, other: TagId) bool {
return std.mem.eql(u8, self.id, other.id);
}
};
pub const RefType = enum {
blob,
tree,
commit,
tag,
};
pub const AnyId = union(RefType) {
blob: BlobId,
tree: TreeId,
commit: CommitId,
tag: TagId,
pub fn erase(self: AnyId) Id {
return switch (self) {
inline else => |v| v.id,
};
}
};
pub fn version(alloc: std.mem.Allocator) !string {
const result = try root.child_process.run(alloc, .cwd(), .ignore, .pipe, .pipe, 1024, &.{ "git", "--version" });
defer alloc.free(result.stdout);
defer alloc.free(result.stderr);
std.debug.assert(result.term == .exited and result.term.exited == 0);
return try alloc.dupe(u8, extras.trimPrefixEnsure(std.mem.trimEnd(u8, result.stdout, "\n"), "git version ").?);
}
/// Returns the result of running `git rev-parse HEAD`
/// dir must already be pointing at the .git folder
pub fn getHEAD(alloc: std.mem.Allocator, dir: nfs.Dir) !?CommitId {
const t = tracer.trace(@src(), "", .{});
defer t.end();
const headfile = dir.readFileAlloc(alloc, "HEAD", 1024) catch |err| switch (err) {
error.ENOENT => return null,
else => |e| return e,
};
defer alloc.free(headfile);
const h = std.mem.trimEnd(u8, headfile, "\n");
if (std.mem.startsWith(u8, h, "ref:")) {
blk: {
var buf: [std.fs.max_path_bytes]u8 = undefined;
@memcpy((&buf).ptr, h[5..]);
buf[h[5..].len] = 0;
const reffile = dir.readFileAlloc(alloc, buf[0..h[5..].len :0], 1024) catch |err| switch (err) {
error.ENOENT => break :blk,
else => |e| return e,
};
defer alloc.free(reffile);
return ensureObjId(CommitId, try alloc.dupe(u8, std.mem.trimEnd(u8, reffile, "\n")));
}
blk: {
const pckedrfs = dir.readFileAlloc(alloc, "packed-refs", 1024 * 1024 * 1024) catch |err| switch (err) {
error.ENOENT => break :blk,
else => |e| return e,
};
defer alloc.free(pckedrfs);
var iter = std.mem.splitScalar(u8, pckedrfs, '\n');
while (iter.next()) |line| {
if (std.mem.startsWith(u8, line, "#")) continue;
if (std.mem.startsWith(u8, line, "^")) continue;
if (line.len == 0) continue;
var jter = std.mem.splitScalar(u8, line, ' ');
const objid = jter.next().?;
const ref = jter.next().?;
std.debug.assert(jter.next() == null);
if (std.mem.eql(u8, h[5..], ref)) return ensureObjId(CommitId, try alloc.dupe(u8, objid));
}
}
return null;
}
return ensureObjId(CommitId, try alloc.dupe(u8, h));
}
// 40 is length of sha1 hash
pub fn ensureObjId(comptime T: type, input: string) T {
extras.assertLog(input.len == 40, "ensureObjId: {s}", .{input});
return .{ .id = input[0..40] };
}
pub fn parseCommit(alloc: std.mem.Allocator, commitfile: string, mailmap: *const std.hash_map.StringHashMapUnmanaged([]const u8), mailmap_names: *const std.hash_map.StringHashMapUnmanaged([]const u8)) !Commit {
const t = tracer.trace(@src(), "", .{});
defer t.end();
var iter = std.mem.splitScalar(u8, commitfile, '\n');
var result: Commit = .{
.raw = commitfile,
.tree = undefined,
.parents = undefined,
.author = undefined,
.committer = undefined,
.gpgsig = "",
.message = undefined,
};
var parents = std.array_list.Managed(CommitId).init(alloc);
errdefer parents.deinit();
var f_start: usize = 0;
while (true) {
const line_start = iter.index.?;
const line = iter.next() orelse break;
if (line.len == 0) break;
const space = std.mem.indexOfScalar(u8, line, ' ').?;
const k = line[0..space];
if (std.mem.eql(u8, k, "tree")) result.tree = .{ .id = line[space + 1 ..][0..40] };
if (std.mem.eql(u8, k, "author")) result.author = try parseCommitUserAndAt(line[space + 1 ..]);
if (std.mem.eql(u8, k, "committer")) result.committer = try parseCommitUserAndAt(line[space + 1 ..]);
if (std.mem.eql(u8, k, "parent")) try parents.append(.{ .id = line[space + 1 ..][0..40] });
if (std.mem.eql(u8, k, "gpgsig")) {
f_start = line_start + 7;
_ = iter.next().?;
while (true) {
const line2_start = iter.index.?;
const line2 = iter.next() orelse break;
if (line2.len == 0 or line2[0] != ' ') {
iter.index = line2_start;
break;
}
}
result.gpgsig = commitfile[f_start .. iter.index.? - 1];
}
}
result.parents = try parents.toOwnedSlice();
result.author.email = mailmap.get(result.author.email) orelse result.author.email;
result.author.name = mailmap_names.get(result.author.email) orelse result.author.name;
result.committer.email = mailmap.get(result.committer.email) orelse result.committer.email;
result.committer.name = mailmap_names.get(result.committer.email) orelse result.committer.name;
result.message = iter.rest();
return result;
}
fn parseCommitUserAndAt(input: string) !UserAndAt {
const t = tracer.trace(@src(), "", .{});
defer t.end();
// Mitchell Hashimoto <mitchell.hashimoto@gmail.com> 1680797363 -0700
// first and second part is https://datatracker.ietf.org/doc/html/rfc5322#section-3.4
// third part is unix epoch timestamp
// fourth part is TZ
var maybe_bad_parser = std.mem.splitBackwardsScalar(u8, input, ' ');
const tz_part = maybe_bad_parser.next() orelse return error.BadCommitTz;
const time_part = maybe_bad_parser.next() orelse return error.BadCommitTime;
var email_part = maybe_bad_parser.next() orelse return error.BadCommitEmail;
while (email_part[0] != '<') {
const next_len = maybe_bad_parser.next().?.len;
email_part.ptr -= next_len + 1;
email_part.len += next_len + 1;
}
const name_part = maybe_bad_parser.rest();
std.debug.assert(email_part[0] == '<');
std.debug.assert(email_part[email_part.len - 1] == '>');
const name = name_part;
const email = std.mem.trim(u8, email_part, "<>");
const at = parseAt(time_part, tz_part);
return .{
.name = name,
.email = email,
.at = at,
};
}
fn parseAt(time_part: string, tz_part: string) time.DateTime {
var at_s = extras.parseDigits(u64, time_part, 10) catch unreachable;
std.debug.assert(tz_part.len == 5);
std.debug.assert(tz_part[0] == '-' or tz_part[0] == '+');
const sign: i8 = if (tz_part[0] == '+') 1 else -1;
const hrs = extras.parseDigits(u7, tz_part[1..][0..2], 10) catch unreachable;
const mins = extras.parseDigits(u7, tz_part[3..][0..2], 10) catch unreachable;
var z_offset: i8 = 0;
z_offset += hrs;
z_offset *= 4;
z_offset += mins / 15;
z_offset *= sign;
at_s = extras.safeAdd(at_s, @as(i32, z_offset) * 15 * time.s_per_min);
var at: time.DateTime = .initUnix(at_s);
at.z_offset = z_offset;
return at;
}
fn parseTreeMode(input: string) !Tree.Object.Mode {
const t = tracer.trace(@src(), "", .{});
defer t.end();
std.debug.assert(input.len == 6);
return .{
.type = @fromBackingInt(@intCast(try extras.parseDigits(u16, input[0..3], 10))),
.perm_user = @bitCast(try extras.parseDigits(u3, input[3..][0..1], 8)),
.perm_group = @bitCast(try extras.parseDigits(u3, input[4..][0..1], 8)),
.perm_other = @bitCast(try extras.parseDigits(u3, input[5..][0..1], 8)),
};
}
// TODO make this inspect .git manually
// TODO make this return a Reader when we implement it ourselves
pub fn getTreeDiff(alloc: std.mem.Allocator, dir: nfs.Dir, commitid: CommitId, parentid: ?CommitId) !string {
const t = tracer.trace(@src(), "", .{});
defer t.end();
if (parentid == null) {
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .pipe, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "-p", "--raw", "--full-index", TreeId.empty.id, commitid.id });
std.debug.assert(result.term == .exited and result.term.exited == 0);
return std.mem.trim(u8, result.stdout, "\n");
}
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .pipe, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "-p", "--raw", "--full-index", parentid.?.id, commitid.id });
std.debug.assert(result.term == .exited and result.term.exited == 0);
return std.mem.trim(u8, result.stdout, "\n");
}
// TODO make this inspect .git manually
pub fn getTreeDiffOnlyStat(alloc: std.mem.Allocator, dir: nfs.Dir, commitid: CommitId, parentid: ?CommitId) !string {
const t = tracer.trace(@src(), "", .{});
defer t.end();
if (parentid == null) {
// 4b825dc642cb6eb9a060e54bf8d69288fbee4904 is a hardcode for the empty tree in git sha1
// result of `printf | git hash-object -t tree --stdin`
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .ignore, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "--stat=2048", "--stat-graph-width=32", "4b825dc642cb6eb9a060e54bf8d69288fbee4904", commitid.id });
std.debug.assert(result.term == .exited and result.term.exited == 0);
return result.stdout;
}
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .ignore, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "--stat=2048", "--stat-graph-width=32", parentid.?.id, commitid.id });
std.debug.assert(result.term == .exited and result.term.exited == 0);
return result.stdout;
}
// TODO make this inspect .git manually
pub fn getTreeDiffOnlyDiff(alloc: std.mem.Allocator, dir: nfs.Dir, commitid: CommitId, parentid: ?CommitId) !string {
const t = tracer.trace(@src(), "", .{});
defer t.end();
if (parentid == null) {
// 4b825dc642cb6eb9a060e54bf8d69288fbee4904 is a hardcode for the empty tree in git sha1
// result of `printf | git hash-object -t tree --stdin`
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .ignore, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "--patch", "--full-index", "--patience", "4b825dc642cb6eb9a060e54bf8d69288fbee4904", commitid.id });
if (!(result.term == .exited and result.term.exited == 0)) std.log.err("{s}", .{result.stderr});
std.debug.assert(result.term == .exited and result.term.exited == 0);
return result.stdout;
}
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .ignore, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "--patch", "--full-index", "--patience", parentid.?.id, commitid.id });
if (!(result.term == .exited and result.term.exited == 0)) std.log.err("{s}", .{result.stderr});
std.debug.assert(result.term == .exited and result.term.exited == 0);
return result.stdout;
}
// TODO make this inspect .git manually
pub fn getFormatPatch(alloc: std.mem.Allocator, dir: nfs.Dir, commitid: CommitId, parentid: ?CommitId) !string {
const t = tracer.trace(@src(), "", .{});
defer t.end();
if (parentid == null) {
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .pipe, 1024 * 1024 * 1024, &.{ "git", "format-patch", "--stdout", "--full-index", "--patience", "--root", commitid.id });
if (!(result.term == .exited and result.term.exited == 0)) std.log.err("{s}", .{result.stderr});
std.debug.assert(result.term == .exited and result.term.exited == 0);
return result.stdout;
}
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .pipe, 1024 * 1024 * 1024, &.{ "git", "format-patch", "--stdout", "--full-index", "--patience", parentid.?.id ++ "..." ++ commitid.id });
if (!(result.term == .exited and result.term.exited == 0)) std.log.err("{s}", .{result.stderr});
std.debug.assert(result.term == .exited and result.term.exited == 0);
return result.stdout;
}
// TODO make this inspect .git manually
// TODO make this return a Reader when we implement it ourselves
pub fn getTreeDiffPath(alloc: std.mem.Allocator, dir: nfs.Dir, commitid: CommitId, parentid: ?CommitId, path: []const u8) !string {
const t = tracer.trace(@src(), "", .{});
defer t.end();
if (parentid == null) {
// 4b825dc642cb6eb9a060e54bf8d69288fbee4904 is a hardcode for the empty tree in git sha1
// result of `printf | git hash-object -t tree --stdin`
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .pipe, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "-p", "--raw", "--full-index", "4b825dc642cb6eb9a060e54bf8d69288fbee4904", commitid.id, "--", path });
std.debug.assert(result.term == .exited and result.term.exited == 0);
return std.mem.trim(u8, result.stdout, "\n");
}
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .pipe, 1024 * 1024 * 1024, &.{ "git", "diff-tree", "-p", "--raw", "--full-index", parentid.?.id, commitid.id, "--", path });
std.debug.assert(result.term == .exited and result.term.exited == 0);
return std.mem.trim(u8, result.stdout, "\n");
}
pub fn parseTreeDiff(alloc: std.mem.Allocator, input: string) !TreeDiff {
const t = tracer.trace(@src(), "", .{});
defer t.end();
var lineiter = std.mem.splitScalar(u8, input, '\n');
var overview = std.array_list.Managed(TreeDiff.StateLine).init(alloc);
var diffs = std.array_list.Managed(TreeDiff.Diff).init(alloc);
var meta = std.mem.zeroes(TreeDiff.Meta);
while (lineiter.next()) |lin| {
if (lin.len == 0) break;
std.debug.assert(lin[0] == ':');
// :100644 100644 c06b41d04c381f1841d445c0072219d9a7f57e17 e8f91cf7dd413ac65a362b0a170951033dba4762 M notes/all_packages.txt
var jter = std.mem.tokenizeScalar(u8, lin[1..], ' ');
const before_mode = try parseTreeMode(jter.next().?);
const after_mode = try parseTreeMode(jter.next().?);
const before_tree = ensureObjId(BlobId, jter.next().?);
const after_tree = ensureObjId(BlobId, jter.next().?);
var kter = std.mem.splitScalar(u8, jter.rest(), '\t');
const action_s = kter.next().?;
try overview.append(.{
.before = .{
.mode = before_mode,
.blob = before_tree,
},
.after = .{
.mode = after_mode,
.blob = after_tree,
},
.action = std.meta.stringToEnum(TreeDiff.Action, action_s).?,
.sub_path = kter.rest(),
});
meta.files_changed += 1;
}
if (lineiter.peek() == null) {
return TreeDiff{
.overview = overview.items,
.diffs = diffs.items,
.meta = meta,
};
}
// diff --git a/notes/all_packages.txt b/notes/all_packages.txt
// index c06b41d..e8f91cf 100644
// --- a/notes/all_packages.txt
// +++ b/notes/all_packages.txt
// @@ -89,3 +89,4 @@ freedesktop/xorg/libsm
// freedesktop/xorg/libxt
// freedesktop/xorg/libxmu
// ncompress
// +freedesktop/xorg/libxpm
blk: while (true) {
const first_line = lineiter.next().?;
std.debug.assert(std.mem.startsWith(u8, first_line, "diff --git"));
var i = diffs.items.len;
var n: usize = 0;
while (n < i) : (n += 1) i -= @intFromBool(overview.items[n].action == .T);
try diffs.append(.{
.index = @splat(.{ .id = "0000000000000000000000000000000000000000" }),
.before_path = overview.items[i].sub_path,
.after_path = overview.items[i].sub_path,
.before_mode = overview.items[i].before.mode,
.after_mode = overview.items[i].after.mode,
.subs = 0,
.adds = 0,
.content = "",
});
const diff = &diffs.items[diffs.items.len - 1];
if (overview.items[i].action == .T) diff.before_mode = .none;
if (overview.items[i].action == .T) diff.after_mode = .none;
while (true) {
if (lineiter.index.? >= input.len) {
break :blk;
}
if (lineiter.peek()) |lin| {
if (std.mem.startsWith(u8, lin, "index")) {
const index = lin[6..];
var iiter = std.mem.splitSequence(u8, index, "..");
var xx: [2][]const u8 = .{ iiter.next().?, iiter.next().? };
std.debug.assert(iiter.next() == null);
if (std.mem.indexOfScalar(u8, xx[1], ' ')) |j| xx[1] = xx[1][0..j];
diff.index[0] = ensureObjId(CommitId, xx[0]);
diff.index[1] = ensureObjId(CommitId, xx[1]);
lineiter.index.? += lin.len + 1;
break;
}
if (extras.trimPrefixEnsure(lin, "new file mode ")) |sl| {
diff.after_mode = parseTreeMode(sl) catch unreachable;
lineiter.index.? += lin.len + 1;
continue;
}
if (extras.trimPrefixEnsure(lin, "deleted file mode ")) |sl| {
diff.before_mode = parseTreeMode(sl) catch unreachable;
lineiter.index.? += lin.len + 1;
continue;
}
if (extras.trimPrefixEnsure(lin, "old mode ")) |sl| {
diff.before_mode = parseTreeMode(sl) catch unreachable;
lineiter.index.? += lin.len + 1;
continue;
}
if (extras.trimPrefixEnsure(lin, "new mode ")) |sl| {
diff.after_mode = parseTreeMode(sl) catch unreachable;
lineiter.index.? += lin.len + 1;
continue;
}
if (std.mem.startsWith(u8, lin, "diff --git")) {
continue :blk;
}
std.log.err("{s}", .{lin});
unreachable;
}
}
var content_start: usize = 0;
while (true) {
if (lineiter.index.? >= input.len) {
break :blk;
}
if (lineiter.peek()) |lin| {
if (std.mem.startsWith(u8, lin, "--- ")) {
diff.before_path = extras.trimPrefix(lin[4..], "a/");
lineiter.index.? += lin.len + 1;
continue;
}
if (std.mem.startsWith(u8, lin, "+++ ")) {
diff.after_path = extras.trimPrefix(lin[4..], "b/");
lineiter.index.? += lin.len + 1;
continue;
}
if (std.mem.startsWith(u8, lin, "@@ ")) {
content_start = lineiter.index.?;
lineiter.index.? += lin.len + 1;
break;
}
if (std.mem.startsWith(u8, lin, "Binary files ")) {
content_start = lineiter.index.?;
lineiter.index.? += lin.len + 1;
break;
}
if (std.mem.startsWith(u8, lin, "diff --git")) {
continue :blk;
}
std.log.err("{s}", .{lin});
unreachable;
}
}
if (lineiter.index.? >= input.len) {
diff.content = input[content_start..];
break :blk;
}
while (true) {
if (lineiter.peek()) |lin| {
if (std.mem.startsWith(u8, lin, "diff --git")) {
const content_end = lineiter.index.? - 1;
diff.content = input[content_start..content_end];
continue :blk;
}
if (lin[0] == '-') {
diff.subs += 1;
meta.lines_removed += 1;
}
if (lin[0] == '+') {
diff.adds += 1;
meta.lines_added += 1;
}
lineiter.index.? += lin.len + 1;
if (lineiter.index.? >= input.len) {
diff.content = input[content_start..];
break :blk;
}
}
}
}
return TreeDiff{
.overview = overview.items,
.diffs = diffs.items,
.meta = meta,
};
}
pub const TreeDiff = struct {
overview: []const StateLine,
diffs: []const Diff,
meta: Meta,
pub const StateLine = struct {
before: State,
after: State,
action: Action,
sub_path: string,
};
pub const State = struct {
mode: Tree.Object.Mode,
blob: BlobId,
};
pub const Action = enum {
A, // Added
C, // Copied
D, // Deleted
M, // Modified
R, // Renamed
T, // type changed
U, // Unmerged
X, // Unknown
B, // Broken
pub fn toString(self: Action, alloc: std.mem.Allocator) !string {
_ = alloc;
return @tagName(self);
}
};
pub const Diff = struct {
index: [2]CommitId,
before_path: string,
after_path: string,
before_mode: Tree.Object.Mode,
after_mode: Tree.Object.Mode,
adds: u32,
subs: u32,
content: string,
};
pub const Meta = struct {
files_changed: u32,
lines_added: u64,
lines_removed: u64,
};
};
pub fn parseTag(tagfile: string) !Tag {
const t = tracer.trace(@src(), "", .{});
defer t.end();
var iter = std.mem.splitScalar(u8, tagfile, '\n');
var result: Tag = .{
.raw = tagfile,
.object = undefined,
.type = undefined,
.tagger = null,
.message = undefined,
};
const object = extras.trimPrefixEnsure(iter.next().?, "object ").?;
std.debug.assert(object.len == 40);
result.object = object[0..40];
const ty = extras.trimPrefixEnsure(iter.next().?, "type ").?;
result.type = std.meta.stringToEnum(RefType, ty).?;
const tag = extras.trimPrefixEnsure(iter.next().?, "tag ").?;
_ = tag;
while (true) {
const line = iter.next() orelse break;
if (line.len == 0) break;
const space = std.mem.indexOfScalar(u8, line, ' ').?;
const k = line[0..space];
if (std.mem.eql(u8, k, "tagger")) result.tagger = try parseCommitUserAndAt(line[space + 1 ..]);
}
result.message = iter.rest();
return result;
}
// TODO make this inspect .git/objects
pub fn getBlame(alloc: std.mem.Allocator, dir: nfs.Dir, at: CommitId, sub_path: string) !string {
const t = tracer.trace(@src(), " {s} -- {s}", .{ at.id, sub_path });
defer t.end();
const result = try root.child_process.run(alloc, dir, .ignore, .pipe, .pipe, 1024 * 1024 * 1024, &.{ "git", "blame", "-p", at.id, "--", sub_path });
extras.assertLog(result.term == .exited and result.term.exited == 0, "{s}", .{result.stderr});
return result.stdout;
}
pub const BlameIterator = struct {
inner: std.mem.SplitIterator(u8, .scalar),
pub fn init(blamefile: []const u8) BlameIterator {
return .{
.inner = std.mem.splitScalar(u8, blamefile, '\n'),
};
}
/// when line.continuity is >0 then .commit will be the same for the next continuity-1 iterations
pub fn next(self: *BlameIterator) ?Line {
var result: Line = .{
.commit = undefined,
.prev_line = 0,
.curr_line = 0,
.continuity = 0,
.author = .{ .name = "", .email = "", .at = .initUnix(0) },
.committer = .{ .name = "", .email = "", .at = .initUnix(0) },
.summary = "",
.previous = null,
.filename = "",
.line = "",
};
blk: {
var it = std.mem.splitScalar(u8, self.inner.next() orelse return null, ' ');
result.commit = ensureObjId(CommitId, extras.nullifyS(it.next().?) orelse return null);
result.prev_line = extras.parseDigits(u32, it.next().?, 10) catch unreachable;
result.curr_line = extras.parseDigits(u32, it.next().?, 10) catch unreachable;
result.continuity = extras.parseDigits(u32, it.next() orelse break :blk, 10) catch unreachable;
}
while (self.inner.next()) |line| {
if (line[0] == '\t') {
result.line = line[1..];
break;
}
if (extras.trimPrefixEnsure(line, "author ")) |trimmed| {
result.author = .{
.name = trimmed,
.email = extras.trimPrefixEnsure(self.inner.next().?, "author-mail ").?,
.at = parseAt(
extras.trimPrefixEnsure(self.inner.next().?, "author-time ").?,
extras.trimPrefixEnsure(self.inner.next().?, "author-tz ").?,
),
};
continue;
}
if (extras.trimPrefixEnsure(line, "committer ")) |trimmed| {
result.committer = .{
.name = trimmed,
.email = extras.trimPrefixEnsure(self.inner.next().?, "committer-mail ").?,
.at = parseAt(
extras.trimPrefixEnsure(self.inner.next().?, "committer-time ").?,
extras.trimPrefixEnsure(self.inner.next().?, "committer-tz ").?,
),
};
continue;
}
if (extras.trimPrefixEnsure(line, "summary ")) |trimmed| {
result.summary = trimmed;
continue;
}
if (extras.trimPrefixEnsure(line, "previous ")) |trimmed| {
var it = std.mem.splitScalar(u8, trimmed, ' ');
result.previous = .{
ensureObjId(CommitId, it.next().?),
it.next().?,
};
continue;
}
if (extras.trimPrefixEnsure(line, "filename ")) |trimmed| {
result.filename = trimmed;
continue;
}
}
return result;
}
pub const Line = struct {
commit: CommitId,
prev_line: u32,
curr_line: u32,
continuity: u32,
author: UserAndAt,
committer: UserAndAt,
summary: string,
previous: ?struct { CommitId, string },
filename: string,
line: string,
};
};
pub const Repository = struct {
gitdir: nfs.Dir,
gpa: std.mem.Allocator,
unpacked_loose_objects: std.StringArrayHashMapUnmanaged(GitObject),
unpacked_objects: std.AutoArrayHashMapUnmanaged(u64, GitObject),
unpacked_objects_window: usize,
idx_content: std.StringArrayHashMapUnmanaged([]const u8),
pack_content: std.StringArrayHashMapUnmanaged([]const u8),
commits: std.StringArrayHashMapUnmanaged(*Commit),
trees: std.StringArrayHashMapUnmanaged(*Tree),
tags: std.StringArrayHashMapUnmanaged(*Tag),
mailmap_content: []const u8,
mailmap: std.hash_map.StringHashMapUnmanaged([]const u8),
mailmap_names: std.hash_map.StringHashMapUnmanaged([]const u8),
pub const CacheBehavior = enum { no_cache, cache };
pub fn init(gitdir: nfs.Dir, gpa: std.mem.Allocator) Repository {
return .{
.gitdir = gitdir,
.gpa = gpa,
.unpacked_loose_objects = .empty,
.unpacked_objects = .empty,
.unpacked_objects_window = 0,
.idx_content = .empty,
.pack_content = .empty,
.commits = .empty,
.trees = .empty,
.tags = .empty,
.mailmap_content = "",
.mailmap = .empty,
.mailmap_names = .empty,
};
}
pub fn deinit(r: *Repository) void {
for (r.unpacked_loose_objects.values()) |v| r.gpa.free(v.content);
r.unpacked_loose_objects.deinit(r.gpa);
for (r.unpacked_objects.values()) |v| r.gpa.free(v.content);
r.unpacked_objects.deinit(r.gpa);
for (r.idx_content.keys()) |k| r.gpa.free(k);
for (r.idx_content.values()) |v| nfs.munmap(v);
r.idx_content.deinit(r.gpa);
for (r.pack_content.values()) |v| nfs.munmap(v);
r.pack_content.deinit(r.gpa);
for (r.commits.values()) |v| v.destroy(r);
r.commits.deinit(r.gpa);
for (r.trees.values()) |v| v.destroy(r);
r.trees.deinit(r.gpa);
for (r.tags.values()) |v| v.destroy(r);
r.tags.deinit(r.gpa);
r.mailmap.deinit(r.gpa);
r.mailmap_names.deinit(r.gpa);
}
pub fn initMailmap(r: *Repository) !void {
const headid = try getHEAD(r.gpa, r.gitdir) orelse return;
const head = try r.getCommitA(headid.id, .cache);
const tree = try r.getTreeA(head.tree.id, .cache);
const blob = tree.get(".mailmap") orelse return;
if (blob.id != .blob) return;
const mailmap_content = try r.getBlobA(blob.id.blob.id, .cache);
var mailmap: std.hash_map.StringHashMapUnmanaged([]const u8) = .empty;
var mailmap_names: std.hash_map.StringHashMapUnmanaged([]const u8) = .empty;
if (mailmap_content.len > 0) {
var iter = std.mem.splitScalar(u8, mailmap_content, '\n');
while (iter.next()) |line| {
if (std.mem.startsWith(u8, line, "#")) continue;
var jter = std.mem.splitScalar(u8, line, '<');
const name = std.mem.trim(u8, jter.next().?, " ");
var first: ?[]const u8 = null;
while (jter.next()) |fntry| {
const email = fntry[0 .. std.mem.indexOfScalar(u8, fntry, '>') orelse continue];
if (first == null) {
first = email;
try mailmap_names.put(r.gpa, email, name);
continue;
}
try mailmap.put(r.gpa, email, first.?);
}
}
}
r.mailmap_content = mailmap_content;
r.mailmap = mailmap;
r.mailmap_names = mailmap_names;
}
pub fn getObject(r: *Repository, oid: Id, cache_behavior: CacheBehavior) anyerror!?GitObject {
const t = tracer.trace(@src(), " {s}", .{oid});
defer t.end();
if (cache_behavior == .cache) if (r.unpacked_loose_objects.get(oid)) |obj| {
return obj;
};
if (oid.len == 40) blk: { //sha1 object
var sub_path: [49:0]u8 = "objects/00/00000000000000000000000000000000000000".*;
@memcpy(sub_path[8..][0..2], oid[0..2]);
@memcpy(sub_path[11..], oid[2..]);
const objfile = r.gitdir.openFile(&sub_path, .{}) catch |err| switch (err) {
error.ENOENT => break :blk,
else => |e| return e,
};
defer objfile.close();
const stat = try objfile.stat();
const compressed_content = try objfile.readAlloc(r.gpa, stat.size);
defer r.gpa.free(compressed_content);
var list: nio.AllocatingWriter = .init(r.gpa);
errdefer list.deinit();
try list.ensureUnusedCapacity(512);
try inflate_decompress(compressed_content, &list);
const data = list.items;
const header = data[0..std.mem.indexOfScalar(u8, data, 0).?];
const _type_s = header[0..std.mem.indexOfScalar(u8, header, ' ').?];
const _type = std.meta.stringToEnum(RefType, _type_s).?;
const content_len = try extras.parseDigits(u64, header[_type_s.len + 1 ..], 10);
list.replaceRangeAssumeCapacity(0, header.len + 1, "");
const content = try list.toOwnedSlice();
std.debug.assert(content.len == content_len);
const obj: GitObject = .{ .type = _type, .content = content };
if (cache_behavior == .cache) try r.unpacked_loose_objects.put(r.gpa, oid, obj);
return obj;
}
// read .idx
if (r.idx_content.count() == 0) {
const t2 = tracer.trace(@src(), " read objects/pack", .{});
defer t2.end();
const packdir = try r.gitdir.openDir("objects/pack", .{});
defer packdir.close();
var iter = packdir.iterate();
while (try iter.next()) |entry| {
const t3 = tracer.trace(@src(), " {s}", .{entry.name});
defer t3.end();
if (entry.type != .REG) continue;
if (!std.mem.endsWith(u8, entry.name, ".idx")) continue;
// std.log.debug("packdir iterate: {s}", .{entry.name});
const idx_file = try packdir.openFile(entry.name, .{});
defer idx_file.close();
const idx_content = try idx_file.mmap();
errdefer nfs.munmap(idx_content);
try r.idx_content.put(
r.gpa,
try r.gpa.dupe(u8, entry.name),
idx_content,
);
}
}
const pack_index, const pack_offset = try r.getObjectPackIndex(oid) orelse return null;
// parse .pack
return try r.getPackedObject(pack_index, pack_offset, cache_behavior);
}
fn getObjectPackIndex(r: *Repository, oid: Id) !?[2]usize {
const t = tracer.trace(@src(), " {s}", .{oid});
defer t.end();
for (r.idx_content.keys(), r.idx_content.values()) |idx_path, idx_content| {
if (std.mem.startsWith(u8, idx_content, "\xfftOc")) {
var idx_fbs: nio.FixedBufferStream([]const u8) = .init(idx_content);
_ = idx_fbs.takeSlice(4);
std.debug.assert(idx_fbs.takeInt(u32, .big) == 2);
const fanout_be_bytes = idx_fbs.takeSlice(255 * 4);
_ = fanout_be_bytes;
const object_count = idx_fbs.takeInt(u32, .big);
const name_bytes = idx_fbs.takeSlice(object_count * 20);
const crc32_bytes = idx_fbs.takeSlice(object_count * 4);
_ = crc32_bytes;
const offsets_be = idx_fbs.takeIntSlice(u32, object_count);
const largeoffsets_be: []align(1) const u64 = @ptrCast(idx_fbs.rest());
// std.sort.binarySearch;
const i = bll: {
var low: usize = 0;
var high: usize = object_count;
while (low < high) {
const mid = low + (high - low) / 2;
const object_id = &extras.to_hex(name_bytes[mid * 20 ..][0..20].*);
switch (std.mem.order(u8, oid, object_id)) {
.eq => break :bll mid,
.gt => low = mid + 1,
.lt => high = mid,
}
}
continue;
};
const pack_offset_candidate = @byteSwap(offsets_be[i]);
const pack_offset = if (pack_offset_candidate & 0x80000000 == 0) pack_offset_candidate else @byteSwap(largeoffsets_be[pack_offset_candidate & 0x7fffffff]);
// std.log.debug("found {s} in {s} at offset {d} {d}", .{ oid, idx_path, pack_offset_candidate, pack_offset });
const pack_index = r.pack_content.getIndex(idx_path) orelse clk: {
var pack_path: [128]u8 = @splat(0);
@memcpy(pack_path[0..13], "objects/pack/");
@memcpy(pack_path[13..][0..idx_path.len], idx_path);
@memcpy(pack_path[13..][idx_path.len - 4 ..][0..5], ".pack");
const pack_name_nidx = std.mem.indexOfScalar(u8, &pack_path, 0).?;
const pack_name = pack_path[0..pack_name_nidx :0];
const pack_file = try r.gitdir.openFile(pack_name, .{});
defer pack_file.close();
const pack_content = try pack_file.mmap();
errdefer nfs.munmap(pack_content);
try r.pack_content.put(r.gpa, idx_path, pack_content);
break :clk r.pack_content.count() - 1;
};
return .{ pack_index, pack_offset };
}
return error.UnexpectedIdxVersion;
}
return null;
}
fn getPackedObject(r: *Repository, pack_index: usize, pack_offset: usize, cache_behavior: CacheBehavior) !GitObject {
const t = tracer.trace(@src(), " {d} {d} {s}", .{ pack_index, pack_offset, r.pack_content.keys()[pack_index] });
defer t.end();
const key = std.hash.Wyhash.hash(0, &(std.mem.toBytes(pack_index) ++ std.mem.toBytes(pack_offset)));
if (cache_behavior == .cache) if (r.unpacked_objects.get(key)) |o| return o;
const pack_content = r.pack_content.values()[pack_index];
if (!std.mem.eql(u8, pack_content[0..4], "PACK")) return error.InvalidGitPack;
const pack_version = std.mem.readInt(u32, pack_content[4..][0..4], .big);
switch (pack_version) {
2 => {
const packedobj_content = pack_content[pack_offset..];
var packedobj_fbs = nio.FixedBufferStream([]const u8).init(packedobj_content);
const PackedObjType = enum(u3) { none, commit, tree, blob, tag, reserved, ofs_delta, ref_delta };
var c: usize = packedobj_fbs.takeArray(1)[0];
const ty: PackedObjType = @fromBackingInt(@intCast((c >> 4) & 7));
var size: usize = c & 15;
var shift: u6 = 4;
while (c & 0x80 > 0) {
c = packedobj_fbs.takeArray(1)[0];
size += (c & 0x7f) << shift;
shift += 7;
}
// std.log.debug("pack_index={d} pack_offset={d} type={s} size={d}", .{ pack_index, pack_offset, @tagName(ty), size });
const t2 = tracer.trace(@src(), " 2 {s} {d}", .{ @tagName(ty), size });
defer t2.end();
switch (ty) {
.none => {
unreachable;
},
.reserved => {
unreachable;
},
.commit, .tree, .blob, .tag => {
const compressed_content = packedobj_fbs.rest();
var list: nio.AllocatingWriter = .init(r.gpa);
errdefer list.deinit();
try list.ensureUnusedCapacity(512);
try inflate_decompress(compressed_content, &list);
const _type = std.meta.stringToEnum(RefType, @tagName(ty)).?;
const content = try list.toOwnedSlice();
const obj: GitObject = .{ .type = _type, .content = content };
const window_max = 1024 * 128;
if (cache_behavior == .cache) {
if (r.unpacked_objects.count() < window_max) {
try r.unpacked_objects.put(r.gpa, key, obj);
} else {
const item = &r.unpacked_objects.values()[r.unpacked_objects_window];
r.gpa.free(item.content);
r.unpacked_objects.keys()[r.unpacked_objects_window] = key;
item.* = obj;
}
r.unpacked_objects_window += 1;
r.unpacked_objects_window %= window_max;
}
return obj;
},
.ofs_delta => {
var offset: usize = 0;
while (true) {
const c2: usize = packedobj_fbs.takeArray(1)[0];
offset = (offset << 7) | (c2 & 0x7f);
if (c2 & 0x80 == 0) break;
offset += 1;
}
const base_pack_offset = pack_offset - offset;
const base_obj = try r.getPackedObject(pack_index, base_pack_offset, cache_behavior);
defer if (cache_behavior == .no_cache) r.gpa.free(base_obj.content);
return r.getDeltadObject(key, &packedobj_fbs, size, base_obj, cache_behavior);
},
.ref_delta => {
const base_oid = extras.to_hex(packedobj_fbs.takeSlice(20)[0..20].*);
const base_obj = (try r.getObject(&base_oid, cache_behavior)).?;
defer if (cache_behavior == .no_cache) r.gpa.free(base_obj.content);
return r.getDeltadObject(key, &packedobj_fbs, size, base_obj, cache_behavior);
},