-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathmain.zig
More file actions
390 lines (362 loc) · 12.6 KB
/
main.zig
File metadata and controls
390 lines (362 loc) · 12.6 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
const builtin = @import("builtin");
const std = @import("std");
const version = @import("options").version;
const argparse = @import("argparse.zig");
const glob = @import("glob.zig");
const templateFill = @import("template.zig").fill;
const HttpClient = @import("http_client.zig");
const Statistics = @import("statistics.zig");
pub const std_options: std.Options = .{
.logFn = logFn,
// Even though we change it later, this is necessary to ensure that debug
// logs aren't stripped in release builds.
.log_level = .debug,
};
var log_level: std.log.Level = switch (builtin.mode) {
.Debug => .debug,
else => .warn,
};
fn logFn(
comptime message_level: std.log.Level,
comptime scope: @TypeOf(.enum_literal),
comptime format: []const u8,
args: anytype,
) void {
if (@intFromEnum(message_level) <= @intFromEnum(log_level)) {
std.log.defaultLog(message_level, scope, format, args);
}
}
const embedded_overview_template = @embedFile("templates/overview.svg");
const embedded_languages_template = @embedFile("templates/languages.svg");
const Args = struct {
access_token: ?[]const u8 = null,
json_input_file: ?[]const u8 = null,
json_output_file: ?[]const u8 = null,
silent: bool = false,
debug: bool = false,
verbose: bool = false,
exclude_repos: ?[]const u8 = null,
exclude_langs: ?[]const u8 = null,
exclude_private: bool = false,
overview_output_file: ?[]const u8 = null,
languages_output_file: ?[]const u8 = null,
overview_template: ?[]const u8 = null,
languages_template: ?[]const u8 = null,
max_retries: ?usize = 25,
version: bool = false,
dump_overview_template: ?[]const u8 = null,
dump_languages_template: ?[]const u8 = null,
const Self = @This();
pub fn init(main_init: std.process.Init) !Self {
return try argparse.parse(main_init, Self, struct {
fn errorCheck(a: Self, stderr: *std.Io.Writer) !bool {
if ((a.access_token == null or a.access_token.?.len == 0) and
a.json_input_file == null and !a.version)
{
try stderr.print(
"You must pass an input file or a GitHub token.\n",
.{},
);
return false;
}
return true;
}
}.errorCheck);
}
pub fn deinit(self: Self, allocator: std.mem.Allocator) void {
inline for (@typeInfo(Self).@"struct".fields) |field| {
switch (@typeInfo(field.type)) {
.optional => |optional| {
switch (@typeInfo(optional.child)) {
.pointer => |pointer| switch (pointer.size) {
.slice => if (@field(self, field.name)) |p|
allocator.free(p),
else => comptime unreachable,
},
.bool, .int => {},
else => comptime unreachable,
}
},
.pointer => |p| switch (p.size) {
.slice => allocator.free(@field(self, field.name)),
else => comptime unreachable,
},
.bool, .int => {},
else => comptime unreachable,
}
}
}
};
fn overview(
arena: *std.heap.ArenaAllocator,
stats: anytype,
template: []const u8,
) ![]const u8 {
const a = arena.allocator();
return templateFill(a, template, stats);
}
fn languages(
arena: *std.heap.ArenaAllocator,
stats: anytype,
template: []const u8,
) ![]const u8 {
const a = arena.allocator();
const progress = try a.alloc([]const u8, stats.languages.count());
const lang_list = try a.alloc([]const u8, stats.languages.count());
for (
stats.languages.keys(),
stats.languages.values(),
progress,
lang_list,
0..,
) |language, count, *progress_s, *lang_s, i| {
const color = stats.language_colors.get(language);
const percent =
100 * if (stats.languages_total == 0)
0.0
else
@as(f64, @floatFromInt(count)) /
@as(f64, @floatFromInt(stats.languages_total));
progress_s.* = try std.fmt.allocPrint(a,
\\<span style="
\\ background-color: {s};
\\ width: {d:.3}%;
\\" class="progress-item"></span>
, .{ color orelse "#000", percent });
lang_s.* = try std.fmt.allocPrint(a,
\\<li style="animation-delay: {d}ms;">
\\ <svg
\\ xmlns="http://www.w3.org/2000/svg"
\\ class="octicon"
\\ style="fill: {s};"
\\ viewBox="0 0 16 16"
\\ version="1.1"
\\ width="16"
\\ height="16"
\\ ><path
\\ fill-rule="evenodd"
\\ d="M8 4a4 4 0 100 8 4 4 0 000-8z"
\\ ></path></svg>
\\ <span class="lang">{s}</span>
\\ <span class="percent">{d:.2}%</span>
\\</li>
\\
, .{ (i + 1) * 150, color orelse "#000", language, percent });
}
return templateFill(
a,
template,
struct { lang_list: []const u8, progress: []const u8 }{
.lang_list = try std.mem.concat(a, u8, lang_list),
.progress = try std.mem.concat(a, u8, progress),
},
);
}
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
const io = init.io;
const args = try Args.init(init);
defer args.deinit(allocator);
if (args.silent) {
log_level = .err;
} else if (args.debug) {
log_level = .debug;
} else if (args.verbose) {
log_level = .info;
}
if (args.version) {
const stdout = std.Io.File.stdout();
var writer = stdout.writer(io, &.{});
try writer.interface.print(
\\GitHub Stats version {s}
\\https://github.com/jstrieb/github-stats
\\Created by Jacob Strieb
\\
, .{version});
return;
}
if (args.dump_overview_template) |path| {
try writeFile(io, path, embedded_overview_template);
return;
}
if (args.dump_languages_template) |path| {
try writeFile(io, path, embedded_languages_template);
return;
}
const exclude_repos =
if (args.exclude_repos) |exclude|
try splitList(allocator, exclude, " ,\t\r\n|\"'\x00")
else
null;
defer if (exclude_repos) |exclude| allocator.free(exclude);
const exclude_langs =
if (args.exclude_langs) |exclude|
try splitList(allocator, exclude, ",\t\r\n|\"'\x00")
else
null;
defer if (exclude_langs) |exclude| allocator.free(exclude);
var stats: Statistics = if (args.json_input_file) |path| stats: {
const data = try readFile(allocator, io, path);
defer allocator.free(data);
break :stats try Statistics.initFromJson(allocator, data);
} else if (args.access_token) |access_token| stats: {
std.log.info("Collecting statistics from GitHub API", .{});
var client: HttpClient = try .init(allocator, io, access_token);
defer client.deinit();
break :stats try Statistics.init(
&client,
allocator,
io,
args.max_retries,
);
} else unreachable;
defer stats.deinit(allocator);
if (args.json_output_file) |path| {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
try writeFile(
io,
path,
try std.json.Stringify.valueAlloc(
arena.allocator(),
stats,
.{ .whitespace = .indent_2 },
),
);
}
var aggregate_stats: struct {
languages: std.array_hash_map.String(u64),
language_colors: std.array_hash_map.String([]const u8),
contributions: usize,
name: []const u8,
languages_total: usize = 0,
stars: usize = 0,
forks: usize = 0,
lines_changed: usize = 0,
views: usize = 0,
repos: usize = 0,
} = .{
.contributions = stats.repo_contributions +
stats.issue_contributions +
stats.commit_contributions +
stats.pr_contributions +
stats.review_contributions,
.languages = try .init(allocator, &.{}, &.{}),
.language_colors = try .init(allocator, &.{}, &.{}),
.name = stats.name,
};
defer aggregate_stats.languages.deinit(allocator);
defer aggregate_stats.language_colors.deinit(allocator);
for (stats.repositories) |repository| {
if (glob.matchAny(exclude_repos orelse &.{}, repository.name) or
(args.exclude_private and repository.private))
{
continue;
}
aggregate_stats.stars += repository.stars;
aggregate_stats.forks += repository.forks;
aggregate_stats.lines_changed += repository.lines_changed;
aggregate_stats.views += repository.views;
aggregate_stats.repos += 1;
if (repository.languages) |langs| for (langs) |language| {
if (glob.matchAny(exclude_langs orelse &.{}, language.name)) {
continue;
}
if (language.color) |color| {
try aggregate_stats.language_colors.put(
allocator,
language.name,
color,
);
}
var total = aggregate_stats.languages.get(language.name) orelse 0;
total += language.size;
try aggregate_stats.languages.put(allocator, language.name, total);
aggregate_stats.languages_total += language.size;
};
}
aggregate_stats.languages.sort(struct {
values: @TypeOf(aggregate_stats.languages.values()),
pub fn lessThan(self: @This(), a: usize, b: usize) bool {
// Sort in reverse order
return self.values[a] > self.values[b];
}
}{ .values = aggregate_stats.languages.values() });
{
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
try writeFile(
io,
args.overview_output_file orelse "overview.svg",
try overview(
&arena,
aggregate_stats,
if (args.overview_template) |template|
try readFile(arena.allocator(), io, template)
else
embedded_overview_template,
),
);
try writeFile(
io,
args.languages_output_file orelse "languages.svg",
try languages(
&arena,
aggregate_stats,
if (args.languages_template) |template|
try readFile(arena.allocator(), io, template)
else
embedded_languages_template,
),
);
}
}
test {
std.testing.refAllDecls(@This());
}
fn readFile(
allocator: std.mem.Allocator,
io: std.Io,
path: []const u8,
) ![]const u8 {
std.log.info("Reading data from '{s}'", .{path});
const in =
if (std.mem.eql(u8, path, "-"))
std.Io.File.stdin()
else
try std.Io.Dir.cwd().openFile(io, path, .{});
defer if (!std.mem.eql(u8, path, "-")) in.close(io);
var read_buffer: [64 * 1024]u8 = undefined;
var reader = in.reader(io, &read_buffer);
return try (&reader.interface).allocRemaining(allocator, .unlimited);
}
fn writeFile(
io: std.Io,
path: []const u8,
data: []const u8,
) !void {
std.log.info("Writing data to '{s}'", .{path});
const out =
if (std.mem.eql(u8, path, "-"))
std.Io.File.stdout()
else
try std.Io.Dir.cwd().createFile(io, path, .{});
defer if (!std.mem.eql(u8, path, "-")) 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();
}
fn splitList(
allocator: std.mem.Allocator,
original: []const u8,
separators: []const u8,
) ![][]const u8 {
var list = try std.ArrayList([]const u8).initCapacity(allocator, 16);
errdefer list.deinit(allocator);
var iterator = std.mem.tokenizeAny(u8, original, separators);
while (iterator.next()) |pattern| {
try list.append(allocator, std.mem.trim(u8, pattern, " "));
}
return try list.toOwnedSlice(allocator);
}