-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.zig
More file actions
407 lines (369 loc) · 12.1 KB
/
cache.zig
File metadata and controls
407 lines (369 loc) · 12.1 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
const std = @import("std");
const contribution_languages = @import("contribution_languages.zig");
pub const ContributionLanguage = contribution_languages.LanguageContribution;
const cache_version = 6;
const CacheEntry = struct {
key: []const u8,
pushed_at: []const u8,
lines_changed: ?u32 = null,
views: ?u32 = null,
contribution_languages: ?[]ContributionLanguage = null,
fn deinit(self: CacheEntry, allocator: std.mem.Allocator) void {
allocator.free(self.key);
allocator.free(self.pushed_at);
if (self.contribution_languages) |languages| {
for (languages) |language| language.deinit(allocator);
allocator.free(languages);
}
}
};
const JsonCache = struct {
version: u32 = cache_version,
entries: []JsonEntry = &.{},
};
const JsonEntry = struct {
key: []const u8,
pushed_at: []const u8,
lines_changed: ?u32 = null,
views: ?u32 = null,
contribution_languages: ?[]ContributionLanguage = null,
};
allocator: std.mem.Allocator,
path: ?[]const u8,
entries: std.ArrayList(CacheEntry) = .empty,
dirty: bool = false,
const Self = @This();
pub fn init(
allocator: std.mem.Allocator,
io: std.Io,
path: ?[]const u8,
) !Self {
var self: Self = .{
.allocator = allocator,
.path = path,
};
errdefer self.deinit();
if (path) |p| {
try self.load(io, p);
}
return self;
}
pub fn deinit(self: *Self) void {
for (self.entries.items) |entry| {
entry.deinit(self.allocator);
}
self.entries.deinit(self.allocator);
}
pub fn keyForRepo(repo_id: []const u8, fallback_name: []const u8) [64]u8 {
var digest: [std.crypto.hash.sha2.Sha256.digest_length]u8 = undefined;
const stable = if (repo_id.len > 0) repo_id else fallback_name;
std.crypto.hash.sha2.Sha256.hash(stable, &digest, .{});
return std.fmt.bytesToHex(digest, .lower);
}
pub fn getLinesChanged(
self: *Self,
key: []const u8,
pushed_at: []const u8,
) ?u32 {
const entry = self.findCurrent(key, pushed_at) orelse return null;
return entry.lines_changed;
}
pub fn getViews(
self: *Self,
key: []const u8,
pushed_at: []const u8,
) ?u32 {
const entry = self.findCurrent(key, pushed_at) orelse return null;
return entry.views;
}
pub fn getContributionLanguages(
self: *Self,
key: []const u8,
pushed_at: []const u8,
) ?[]const ContributionLanguage {
const entry = self.findCurrent(key, pushed_at) orelse return null;
return entry.contribution_languages;
}
pub fn putLinesChanged(
self: *Self,
key: []const u8,
pushed_at: []const u8,
lines_changed: u32,
) !void {
const entry = try self.getOrPut(key, pushed_at);
if (entry.lines_changed != lines_changed) {
entry.lines_changed = lines_changed;
self.dirty = true;
}
}
pub fn putViews(
self: *Self,
key: []const u8,
pushed_at: []const u8,
views: u32,
) !void {
const entry = try self.getOrPut(key, pushed_at);
if (entry.views != views) {
entry.views = views;
self.dirty = true;
}
}
pub fn putContributionLanguages(
self: *Self,
key: []const u8,
pushed_at: []const u8,
contribution_languages_: []const ContributionLanguage,
) !void {
const entry = try self.getOrPut(key, pushed_at);
if (entry.contribution_languages) |languages| {
for (languages) |language| language.deinit(self.allocator);
self.allocator.free(languages);
entry.contribution_languages = null;
}
entry.contribution_languages = try contribution_languages.dupeAll(
self.allocator,
contribution_languages_,
);
self.dirty = true;
}
pub fn save(self: *Self, io: std.Io) !void {
const path = self.path orelse return;
if (!self.dirty) return;
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
const a = arena.allocator();
const json_entries = try a.alloc(JsonEntry, self.entries.items.len);
for (self.entries.items, json_entries) |entry, *json_entry| {
json_entry.* = .{
.key = entry.key,
.pushed_at = entry.pushed_at,
.lines_changed = entry.lines_changed,
.views = entry.views,
.contribution_languages = entry.contribution_languages,
};
}
const rendered = try std.json.Stringify.valueAlloc(
a,
JsonCache{ .version = cache_version, .entries = json_entries },
.{ .whitespace = .indent_2 },
);
try writeFile(io, path, rendered);
self.dirty = false;
std.log.info("Saved repository stats cache to '{s}'", .{path});
}
fn load(self: *Self, io: std.Io, path: []const u8) !void {
var file = std.Io.Dir.cwd().openFile(io, path, .{}) catch |err| switch (err) {
error.FileNotFound => {
std.log.info("No repository stats cache found at '{s}'", .{path});
return;
},
else => return err,
};
defer file.close(io);
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
var read_buffer: [64 * 1024]u8 = undefined;
var reader = file.reader(io, &read_buffer);
const data = try (&reader.interface).allocRemaining(arena.allocator(), .unlimited);
const parsed = std.json.parseFromSliceLeaky(
JsonCache,
arena.allocator(),
data,
.{ .ignore_unknown_fields = true, .allocate = .alloc_always },
) catch |err| {
std.log.warn("Ignoring unreadable repository stats cache: {s}", .{@errorName(err)});
return;
};
const load_contribution_languages = parsed.version == cache_version;
try self.entries.ensureTotalCapacity(self.allocator, parsed.entries.len);
for (parsed.entries) |entry| {
if (entry.key.len == 0 or entry.pushed_at.len == 0) continue;
self.entries.appendAssumeCapacity(.{
.key = try self.allocator.dupe(u8, entry.key),
.pushed_at = try self.allocator.dupe(u8, entry.pushed_at),
.lines_changed = entry.lines_changed,
.views = entry.views,
.contribution_languages = if (load_contribution_languages)
if (entry.contribution_languages) |languages|
try contribution_languages.dupeAll(self.allocator, languages)
else
null
else
null,
});
}
std.log.info(
"Loaded repository stats cache with {d} entr{s}",
.{ self.entries.items.len, if (self.entries.items.len == 1) "y" else "ies" },
);
}
fn findCurrent(
self: *Self,
key: []const u8,
pushed_at: []const u8,
) ?*CacheEntry {
const entry = self.findByKey(key) orelse return null;
if (!std.mem.eql(u8, entry.pushed_at, pushed_at)) return null;
return entry;
}
fn findByKey(self: *Self, key: []const u8) ?*CacheEntry {
for (self.entries.items) |*entry| {
if (std.mem.eql(u8, entry.key, key)) return entry;
}
return null;
}
fn getOrPut(
self: *Self,
key: []const u8,
pushed_at: []const u8,
) !*CacheEntry {
if (self.findByKey(key)) |entry| {
if (!std.mem.eql(u8, entry.pushed_at, pushed_at)) {
const new_pushed_at = try self.allocator.dupe(u8, pushed_at);
self.allocator.free(entry.pushed_at);
entry.pushed_at = new_pushed_at;
entry.lines_changed = null;
entry.views = null;
if (entry.contribution_languages) |languages| {
for (languages) |language| language.deinit(self.allocator);
self.allocator.free(languages);
entry.contribution_languages = null;
}
self.dirty = true;
}
return entry;
}
try self.entries.append(self.allocator, .{
.key = try self.allocator.dupe(u8, key),
.pushed_at = try self.allocator.dupe(u8, pushed_at),
});
self.dirty = true;
return &self.entries.items[self.entries.items.len - 1];
}
fn writeFile(io: std.Io, path: []const u8, data: []const u8) !void {
if (std.fs.path.dirname(path)) |parent| {
if (parent.len > 0) {
try std.Io.Dir.cwd().createDirPath(io, parent);
}
}
const out = try std.Io.Dir.cwd().createFile(io, path, .{});
defer out.close(io);
var write_buffer: [64 * 1024]u8 = undefined;
var writer = out.writer(io, &write_buffer);
try writer.interface.writeAll(data);
try writer.interface.flush();
}
test "v1 cache loads without contribution languages" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const path = try std.fmt.allocPrint(
std.testing.allocator,
".zig-cache/tmp/{s}/repo_stats_cache.json",
.{tmp.sub_path},
);
defer std.testing.allocator.free(path);
try writeFile(std.testing.io, path,
\\{
\\ "version": 1,
\\ "entries": [
\\ {
\\ "key": "repo-key",
\\ "pushed_at": "2026-01-01T00:00:00Z",
\\ "lines_changed": 42,
\\ "views": 7
\\ }
\\ ]
\\}
);
var cache = try Self.init(std.testing.allocator, std.testing.io, path);
defer cache.deinit();
try std.testing.expectEqual(
@as(?u32, 42),
cache.getLinesChanged("repo-key", "2026-01-01T00:00:00Z"),
);
try std.testing.expectEqual(
@as(?u32, 7),
cache.getViews("repo-key", "2026-01-01T00:00:00Z"),
);
try std.testing.expect(cache.getContributionLanguages(
"repo-key",
"2026-01-01T00:00:00Z",
) == null);
}
test "v5 contribution languages are ignored after generated-path cache bump" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const path = try std.fmt.allocPrint(
std.testing.allocator,
".zig-cache/tmp/{s}/repo_stats_cache.json",
.{tmp.sub_path},
);
defer std.testing.allocator.free(path);
try writeFile(std.testing.io, path,
\\{
\\ "version": 5,
\\ "entries": [
\\ {
\\ "key": "repo-key",
\\ "pushed_at": "2026-01-01T00:00:00Z",
\\ "lines_changed": 42,
\\ "views": 7,
\\ "contribution_languages": [
\\ { "name": "Other", "color": "#ededed", "lines_changed": 42 }
\\ ]
\\ }
\\ ]
\\}
);
var cache = try Self.init(std.testing.allocator, std.testing.io, path);
defer cache.deinit();
try std.testing.expectEqual(
@as(?u32, 42),
cache.getLinesChanged("repo-key", "2026-01-01T00:00:00Z"),
);
try std.testing.expect(cache.getContributionLanguages(
"repo-key",
"2026-01-01T00:00:00Z",
) == null);
}
test "v6 contribution languages round-trip and invalidate on pushedAt change" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const path = try std.fmt.allocPrint(
std.testing.allocator,
".zig-cache/tmp/{s}/repo_stats_cache.json",
.{tmp.sub_path},
);
defer std.testing.allocator.free(path);
const languages = [_]ContributionLanguage{
.{ .name = "Zig", .color = "#ec915c", .lines_changed = 12 },
.{ .name = "C", .color = "#555555", .lines_changed = 3 },
};
{
var cache = try Self.init(std.testing.allocator, std.testing.io, path);
defer cache.deinit();
try cache.putLinesChanged("repo-key", "2026-01-01T00:00:00Z", 15);
try cache.putContributionLanguages(
"repo-key",
"2026-01-01T00:00:00Z",
&languages,
);
try cache.save(std.testing.io);
}
{
var cache = try Self.init(std.testing.allocator, std.testing.io, path);
defer cache.deinit();
const cached = cache.getContributionLanguages(
"repo-key",
"2026-01-01T00:00:00Z",
).?;
try std.testing.expectEqual(@as(usize, 2), cached.len);
try std.testing.expectEqualStrings("Zig", cached[0].name);
try std.testing.expectEqual(@as(u32, 12), cached[0].lines_changed);
try cache.putLinesChanged("repo-key", "2026-02-01T00:00:00Z", 1);
try std.testing.expect(cache.getContributionLanguages(
"repo-key",
"2026-02-01T00:00:00Z",
) == null);
}
}