-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_check.zig
More file actions
441 lines (388 loc) · 15.2 KB
/
git_check.zig
File metadata and controls
441 lines (388 loc) · 15.2 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
//
// May you do good and not evil.
// May you find forgiveness for yourself and forgive others.
// May you share freely, never taking more than you give.
// May you stand for good principles.
// May we be generation zero to give generations to come the change to be generation 1.
// Adapted from sqlite LICENESE.md , this work is produced under apache 2.0v license.
const std = @import("std");
const ArrayList = std.ArrayList;
const HashMap = std.AutoArrayHashMapUnmanaged;
const StringHashMap = std.StringHashMapUnmanaged;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.gitcheck);
// use <M-s h .> to highlight symbol at point. useful to color different variables
const ctime = @cImport(@cInclude("time.h"));
const TimeCache = struct {
time_format: ?[timestamp_format_len:0]u8 = null,
update_file: bool = true,
const timestamp_format_len = "2023-10-07T06:13".len + 1; // need extra space for '\0'
const cache_filename = ".cache_gitcheck";
fn getCurrentTimestampISO8601(time_format_buf: []u8) [:0]u8 {
assert(time_format_buf.len >= timestamp_format_len);
const ts: i64 = std.time.timestamp();
// NOTE(2025-10-26T22:13:12+02:00): couldn't get to use gmtime_s on windows because of a problem with linking
// so we get libc to allocate memory (¯\_(ツ)_/¯). And if you're wondering why I am not freeing memory,
// this is why.
// Nobyte exists on purpose. Nobyte has real address. all bytes go back to the kernel. Come watch TV
const tm: *ctime.tm = ctime.gmtime(&ts);
const bytes_written = ctime.strftime(
time_format_buf.ptr,
timestamp_format_len,
"%FT%R",
tm,
);
if (bytes_written == 0) {
assert(false and "first assert didn't catch the bug"); // use tigerstyle bo!
time_format_buf[0] = 0;
return time_format_buf[0..1 :0];
}
const time_format = time_format_buf[0..bytes_written :0];
return time_format;
}
fn getLastTimestamp(self: *TimeCache) ![timestamp_format_len]u8 {
if (self.time_format) |tf| {
return tf;
}
const cwd = std.fs.cwd();
// defer cwd.close();
log.debug("cache file |{s}|", .{cache_filename});
if (cwd.openFile(cache_filename, .{ .mode = .read_write })) |cache_file| {
var freader = cache_file.reader(&.{});
const reader = &freader.interface;
self.time_format = undefined;
try reader.readSliceAll(&self.time_format.?);
// NOTE(2025-10-26T23:21:12+02:00): validate?
var new_timestamp_buf: [timestamp_format_len]u8 = undefined;
const new_timestamp = getCurrentTimestampISO8601(&new_timestamp_buf);
if (self.update_file) {
var fwriter = cache_file.writer(&.{});
try fwriter.seekTo(0);
const writer = &fwriter.interface;
try writer.writeAll(new_timestamp);
try writer.flush();
// don't forget to flush. and handle zero byte
try cache_file.setEndPos(new_timestamp.len + 1);
}
cache_file.close();
return self.time_format.?;
} else |err| switch (err) {
error.FileNotFound => {
self.time_format = undefined;
_ = getCurrentTimestampISO8601(&self.time_format.?);
const cache_file = try cwd.createFile(cache_filename, .{});
var fwriter = cache_file.writer(&.{});
const writer = &fwriter.interface;
try writer.writeAll(&self.time_format.?);
try writer.flush();
cache_file.close();
return self.time_format.?;
},
else => return err,
}
}
};
pub fn main() !void {
// try mainEntry();
// try testLogger();
try mainEntry();
}
fn mainEntry() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
const allocator = gpa.allocator();
defer {
// const status = gpa.deinit();
// if(status == .leak) {
// @panic("there was a leak. call a plumber");
// }
}
const scratch = try allocator.alloc(u8, 1024 * 10);
defer allocator.free(scratch);
var args = try std.process.argsWithAllocator(allocator);
_ = args.skip();
var stdout_buffer: [1024]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
const stdout = &stdout_writer.interface;
if (true) {
try stdout.print("Salam\r\n", .{});
stdout.flush() catch {};
}
const dir_init_capacity = 1 << 16; // 640KiB is ought to be enough right?
// andrewk I am waiting for deque that you removed and promised back!
// var directory_queue: std.Deque(std.fs.Dir) = try .initCapacity(allocator, dir_init_capacity);
var directory_queue: RingBuffer(std.fs.Dir) = try .initCapacity(allocator, dir_init_capacity);
defer {
// if (directory_queue.len != 0) {
if (!isEmpty(directory_queue)) {
log.warn("I thought I passed over all directories", .{});
var it = directory_queue.iterator();
while (it.next()) |dir| {
dir.close();
}
}
directory_queue.deinit(allocator);
}
const cwd = std.fs.cwd();
{
var i: usize = 0;
while (args.next()) |path| : (i += 1) {
const top_directory = openDir(cwd, path) catch |err| switch (err) {
error.FileNotFound => {
log.warn("Couldn't open the directroy {s}. it doesn't exist", .{path});
return;
},
else => return err,
};
if (false) {
const dir_name = try dirName(top_directory, scratch);
try log.debug("opened top_directory {s}", .{dir_name});
}
try directory_queue.pushBack(allocator, top_directory);
} else if (i == 0) {
// I want to petition for oxford dictionary to add directroy as a valid spelling.
const top_directory = try openDir(cwd, ".");
try directory_queue.pushBack(allocator, top_directory);
}
}
// cwd.close(); // this is illegal according to zig doc. https://ziglang.org/documentation/0.51.1/std/#std.fs.cwd
var tc = TimeCache{ .update_file = true };
const last_date = try tc.getLastTimestamp();
var dir_name_arena_context = std.heap.ArenaAllocator.init(allocator);
defer dir_name_arena_context.deinit();
const dir_arena = dir_name_arena_context.allocator();
var arena_context = std.heap.ArenaAllocator.init(allocator);
defer arena_context.deinit();
const arena = arena_context.allocator();
const print_all = false;
const git_dotfile = ".git";
const default_last_commit: []const u8 = "HEAD~";
var gitdir_changes: StringHashMap(FilesInsertionsDeletions) = .empty;
defer gitdir_changes.deinit(allocator);
// TODO(2025-10-27T12:49:37+02:00): remove duplicates.
// will never be done unless I am really bored.
while (directory_queue.front()) |directory| {
if (directory.access(git_dotfile, .{})) {
const dir_name = try dirName(directory.*, scratch);
log.info("git-diff {s}", .{dir_name});
const last_commit = getLastCommit(arena, dir_name, &last_date) catch default_last_commit;
const stripped_stdout = try executeGitDiff(arena, dir_name, last_commit);
log.info("\t|{s}|", .{stripped_stdout});
const files_insertions_deletions = parseGitDiff(stripped_stdout);
const persistent_dir_name = try dir_arena.dupe(u8, dir_name);
try gitdir_changes.put(allocator, persistent_dir_name, files_insertions_deletions);
_ = arena_context.reset(.retain_capacity);
} else |git_err| switch (git_err) {
error.FileNotFound => {
var it = directory.iterate();
while (it.next()) |dir| {
if (dir) |d| {
switch (d.kind) {
.directory => {
const d_name = try subdirName(directory.*, d.name, scratch);
// Don't want to search hidden directory for .git
if ('.' != d.name[0]) {
const dir_handle = try openDir(directory.*, d.name);
if (print_all) {
std.debug.print("got directroy {s} with fd {}.\n", .{ d_name, dir_handle.fd });
}
try directory_queue.pushBack(allocator, dir_handle);
}
},
else => {},
}
} else break;
} else |it_err| switch (it_err) {
error.Unexpected => {
log.err("encountered an unexpected error. Iterator {any}", .{it});
},
else => |e| {
log.err("encountered error {any}", .{e});
},
}
},
else => |e| {
log.err("failed to find {s} with error {any}", .{ git_dotfile, e });
},
}
directory.close();
_ = directory_queue.popFront();
}
const max_dir_len: usize = blk: {
var l: usize = 0;
var it = gitdir_changes.keyIterator();
while (it.next()) |key_ptr| {
l = @max(l, key_ptr.len);
}
break :blk l;
};
{
var it = gitdir_changes.iterator();
while (it.next()) |entry| {
try stdout.print("{s}", .{entry.key_ptr.*});
try stdout.splatByteAll(' ', max_dir_len - entry.key_ptr.len);
try stdout.print(" -> {any}\r\n", .{entry.value_ptr.*});
}
stdout.flush() catch {};
}
}
fn getLastCommit(allocator: Allocator, dir_name: []const u8, last_date: []const u8) ![]const u8 {
const result = try std.process.Child.run(.{
.allocator = allocator,
.argv = &.{
"git",
"log",
"--reverse",
"--no-decorate",
"--date-order",
"--pretty=format:%H",
"--after",
last_date, //"2023-10-7T06:13",
},
.cwd = dir_name,
});
const last_commit = result.stdout[0..skipUntil(result.stdout, '\n')];
return try allocator.dupe(u8, last_commit);
}
const FilesInsertionsDeletions = [3]u32;
pub fn parseGitDiff(git_diff: []const u8) FilesInsertionsDeletions {
var result: FilesInsertionsDeletions = .{0} ** 3;
var it = std.mem.splitScalar(u8, git_diff, ',');
for (0..3) |i| {
if (it.next()) |buf| {
if (buf.len > 1) {
const start = buf[1..];
const j = skipUntil(start, ' ');
const num = start[0..j];
result[i] = parseInt(num) catch 0;
}
} else break;
}
return result;
}
fn executeGitDiff(allocator: Allocator, dir_name: []const u8, last_commit_hash: []const u8) ![]const u8 {
const result = try std.process.Child.run(.{
.allocator = allocator,
.argv = &.{ "git", "diff", "--shortstat", last_commit_hash },
.cwd = dir_name,
});
const stripped_stdout = std.mem.trimEnd(u8, result.stdout, "\r\n");
return try allocator.dupe(u8, stripped_stdout);
}
fn parseInt(buf: []const u8) std.fmt.ParseIntError!u32 {
return try std.fmt.parseInt(u32, buf, 10);
}
fn subdirName(d: std.fs.Dir, subdir: []const u8, scratch: []u8) ![]u8 {
return d.realpath(subdir, scratch);
}
fn dirName(d: std.fs.Dir, scratch: []u8) ![]u8 {
return d.realpath(".", scratch);
}
fn openDir(parent_dir: std.fs.Dir, sub_dir: []const u8) !std.fs.Dir {
return try parent_dir.openDir(sub_dir, .{ .iterate = true });
}
pub fn skipUntil(buf: []const u8, char: u8) usize {
for (0..buf.len) |i| {
if (buf[i] == char) {
return i;
}
}
return buf.len;
}
fn RingBuffer(T: type) type {
return struct {
buff: []T,
start: usize = 0,
end: usize = 0,
const Self = @This();
fn initCapacity(allocator: Allocator, len: usize) !Self {
const b = try allocator.alloc(T, len);
return .{
.buff = b,
};
}
fn empty(self: Self) bool {
return self.start % self.size2() == self.end;
}
fn full(self: Self) bool {
return (self.start + self.size()) % self.size2() == self.end;
}
fn size(self: Self) usize {
return self.buff.len;
}
fn size2(self: Self) usize {
return 2 * self.size();
}
fn front(self: *Self) ?*T {
if (self.empty()) {
return null;
} else {
return &self.buff[self.start % self.size()];
}
}
fn popFront(self: *Self) ?*T {
if (self.empty()) {
return null;
} else {
const s = self.start;
self.start = (self.start + 1) % self.size2();
return &self.buff[s % self.size()];
}
}
fn pushBack(self: *Self, _: Allocator, d: T) error{Full}!void {
if (self.full()) {
return error.Full;
}
self.buff[self.end % self.size()] = d;
self.end = (self.end + 1) % self.size2();
}
fn deinit(self: *Self, gpa: Allocator) void {
gpa.free(self.buff);
}
fn iterator(self: *Self) Iterator {
return .{
.rb = self,
.index = self.start,
};
}
const Iterator = struct {
rb: *Self,
index: usize,
fn next(self: *Iterator) ?*T {
if (self.index == self.rb.end) {
return null;
}
const d = &self.rb.buff[self.index % self.rb.size()];
self.index = (self.index + 1) % self.rb.size2();
return d;
}
};
};
}
// there was a testRingBuffer() but it was a basic one so I removed it to save myself the embarrassment
fn isEmpty(q: anytype) bool {
return q.empty();
}
const Logger = struct {
file: std.fs.File,
file_writer: std.fs.File.Writer,
buff: [1024]u8 = undefined,
fn init(parent_dir: std.fs.Dir, filename: []const u8) !Logger {
var logger: Logger = undefined;
logger.file = try parent_dir.createFile(filename, .{});
logger.file_writer = logger.file.writer(&logger.buff);
return logger;
}
fn writer(self: *Logger) *std.Io.Writer {
return &self.file_writer.interface;
}
};
fn testLogger() !void {
const l: Logger = undefined;
std.debug.print("{}, {}, {}\r\n", .{
@sizeOf(@TypeOf(l)),
@sizeOf(std.fs.File),
@sizeOf(std.fs.File.Writer),
});
}
// [^1]: yes I know how to use fancy. I fancy sometimes being.