blob: 97918e07852ac9ed66122772bdd0f32e99b1570f (plain)
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
/*
 * The statistics page, which counts commits per author across a window of
 * recent weeks, months, quarters or years. The window sizes live in one table
 * here, which cgit.c also resolves the max-stats setting against so a
 * repository can refuse the coarser windows. The page reads no diff and no
 * blob contents, so the whole thing costs about one rev-list.
 */

#define USE_THE_REPOSITORY_VARIABLE

#include "cgit.h"
#include "html.h"
#include "parsing.h"
#include "shared.h"
#include "ui-shared.h"
#include "ui-stats.h"

#define DEFAULT_AUTHOR_ROWS 10

/*
 * One author's share of the window. periods is keyed by the label of a
 * period, with the commit count stored in the util field itself rather than
 * behind another allocation.
 */
struct authorstat {
	long total;
	struct string_list periods;
};

static void trunc_week(struct tm *tm)
{
	time_t t = timegm(tm);

	// tm_wday counts from Sunday, while the label comes from %V and %G,
	// which number the ISO weeks that start on Monday.
	t -= ((tm->tm_wday + 6) % 7) * SECONDS_PER_DAY;
	gmtime_r(&t, tm);
}

static void dec_week(struct tm *tm)
{
	time_t t = timegm(tm);

	t -= SECONDS_PER_WEEK;
	gmtime_r(&t, tm);
}

static void inc_week(struct tm *tm)
{
	time_t t = timegm(tm);

	t += SECONDS_PER_WEEK;
	gmtime_r(&t, tm);
}

static char *pretty_week(struct tm *tm)
{
	static char buf[10];

	// A year of five digits or more does not fit, and strftime then leaves
	// the buffer with contents the standard says nothing about, so empty it
	// rather than return whatever the last week left.
	if (!strftime(buf, sizeof(buf), "W%V %G", tm))
		buf[0] = '\0';
	return buf;
}

static void trunc_month(struct tm *tm)
{
	tm->tm_mday = 1;
}

static void dec_month(struct tm *tm)
{
	tm->tm_mon--;
	if (tm->tm_mon < 0) {
		tm->tm_year--;
		tm->tm_mon = 11;
	}
}

static void inc_month(struct tm *tm)
{
	tm->tm_mon++;
	if (tm->tm_mon > 11) {
		tm->tm_year++;
		tm->tm_mon = 0;
	}
}

static char *pretty_month(struct tm *tm)
{
	static const char *months[] = {
		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
	};
	return cgit_fmt("%s %d", months[tm->tm_mon], tm->tm_year + 1900);
}

static void trunc_quarter(struct tm *tm)
{
	trunc_month(tm);
	while (tm->tm_mon % 3 != 0)
		dec_month(tm);
}

static void dec_quarter(struct tm *tm)
{
	dec_month(tm);
	dec_month(tm);
	dec_month(tm);
}

static void inc_quarter(struct tm *tm)
{
	inc_month(tm);
	inc_month(tm);
	inc_month(tm);
}

static char *pretty_quarter(struct tm *tm)
{
	return cgit_fmt("Q%d %d", tm->tm_mon / 3 + 1, tm->tm_year + 1900);
}

static void trunc_year(struct tm *tm)
{
	trunc_month(tm);
	tm->tm_mon = 0;
}

static void dec_year(struct tm *tm)
{
	tm->tm_year--;
}

static void inc_year(struct tm *tm)
{
	tm->tm_year++;
}

static char *pretty_year(struct tm *tm)
{
	return cgit_fmt("%d", tm->tm_year + 1900);
}

/*
 * The order runs from the finest window to the coarsest, because a repository
 * caps the page by storing an index into this table as its max-stats.
 */
static const struct cgit_period periods[] = {
	{'w', "week", 12, 4, trunc_week, dec_week, inc_week, pretty_week},
	{'m', "month", 12, 4, trunc_month, dec_month, inc_month, pretty_month},
	{'q', "quarter", 12, 4, trunc_quarter, dec_quarter, inc_quarter, pretty_quarter},
	{'y', "year", 12, 4, trunc_year, dec_year, inc_year, pretty_year},
};

static void window_start(const struct cgit_period *period, struct tm *tm)
{
	time_t now;
	int i;

	time(&now);
	gmtime_r(&now, tm);
	period->trunc(tm);
	for (i = 1; i < period->count; i++)
		period->dec(tm);
}

static void add_commit(struct string_list *authors, struct commitinfo *info,
		       const struct cgit_period *period)
{
	struct string_list_item *author, *bucket;
	struct authorstat *stats;
	char *name, *label;
	struct tm date;
	time_t when;
	uintptr_t *count;

	// A commit can lack an author header, so fall back rather than
	// handing xstrdup a NULL.
	name = xstrdup(info->author ? info->author : "(unknown)");
	author = string_list_insert(authors, name);
	if (!author->util)
		author->util = xcalloc(1, sizeof(struct authorstat));
	else
		free(name);
	stats = author->util;
	when = info->committer_date;
	// A crafted commit can carry a date outside the range gmtime_r can
	// represent, which would leave date uninitialized and later index the
	// month table out of bounds.
	if (!gmtime_r(&when, &date))
		return;
	period->trunc(&date);
	label = xstrdup(period->pretty(&date));
	bucket = string_list_insert(&stats->periods, label);
	count = (uintptr_t *)&bucket->util;
	if (*count)
		free(label);
	(*count)++;

	stats->total++;
}

/*
 * Count the commits in the displayed window, returning a list of authors
 * whose util field holds a struct authorstat. Merge commits are left out, so
 * that pulling a branch in does not credit the merger with its commits.
 */
static struct string_list collect_stats(const struct cgit_period *period)
{
	struct string_list authors;
	struct rev_info rev;
	struct commit *commit;
	// setup_revisions reads the entries after the double dash up to a
	// NULL, past the count, so the sentinel has to stay even when the
	// path fills the slot before it.
	const char *argv[] = {NULL, ctx.qry.head, NULL, NULL, NULL};
	int argc = 2;
	time_t since;
	struct tm tm;

	window_start(period, &tm);
	since = timegm(&tm);

	if (ctx.qry.path) {
		argv[2] = "--";
		argv[3] = ctx.qry.path;
		argc += 2;
	}
	repo_init_revisions(the_repository, &rev, NULL);
	rev.abbrev = DEFAULT_ABBREV;
	rev.commit_format = CMIT_FMT_DEFAULT;
	rev.max_parents = 1;
	rev.verbose_header = 1;
	rev.show_root_diff = 0;
	// setup_revisions reads argv the way main does and ignores the first
	// entry, so the head to walk sits at argv[1].
	setup_revisions(argc, argv, &rev, NULL);
	// Prune the walk to the displayed window instead of traversing the
	// whole history and discarding older commits. The check below still
	// bounds the period edge exactly.
	rev.max_age = since;
	prepare_revision_walk(&rev);
	memset(&authors, 0, sizeof(authors));
	while ((commit = get_revision(&rev)) != NULL) {
		struct commitinfo *info = cgit_parse_commit(commit);

		if ((time_t)info->committer_date >= since)
			add_commit(&authors, info, period);

		cgit_free_commitinfo(info);
		release_commit_memory(the_repository->parsed_objects, commit);
		commit->parents = NULL;
	}
	return authors;
}

static int cmp_total_commits(const void *a, const void *b)
{
	const struct string_list_item *first = a;
	const struct string_list_item *second = b;
	const struct authorstat *first_stats = first->util;
	const struct authorstat *second_stats = second->util;

	// Report the sign only, since a long difference truncated to int
	// could flip and leave the comparator inconsistent.
	if (second_stats->total > first_stats->total)
		return 1;
	if (second_stats->total < first_stats->total)
		return -1;
	return 0;
}

/*
 * The column labels for the displayed window, oldest first. pretty hands back
 * a buffer it goes on to reuse, so the labels are copied here once and shared
 * by every table below.
 */
static struct string_list build_period_labels(const struct cgit_period *period)
{
	struct string_list labels = STRING_LIST_INIT_DUP;
	struct tm tm;
	int i;

	window_start(period, &tm);
	for (i = 0; i < period->count; i++) {
		string_list_append(&labels, period->pretty(&tm));
		period->inc(&tm);
	}
	return labels;
}

/*
 * The run of authors to sum is given as a start and a count rather than as
 * two indices, so that an empty author list cannot describe a run that wraps.
 */
static void print_summary_row(struct string_list *authors, size_t from,
			      size_t count, const char *label_format,
			      const char *leftclass, const char *centerclass,
			      const char *rightclass,
			      const struct string_list *labels)
{
	struct authorstat *stats;
	struct string_list_item *bucket;
	size_t i, column;
	long total, subtotal;

	total = 0;
	htmlf("<tr><td class='%s'>%s</td>", leftclass,
		cgit_fmt(label_format, (long)count));
	for (column = 0; column < labels->nr; column++) {
		const char *label = labels->items[column].string;

		subtotal = 0;
		for (i = from; i < from + count; i++) {
			stats = authors->items[i].util;
			bucket = string_list_lookup(&stats->periods, label);
			if (bucket)
				subtotal += (uintptr_t)bucket->util;
		}
		htmlf("<td class='%s'>%ld</td>", centerclass, subtotal);
		total += subtotal;
	}
	htmlf("<td class='%s'>%ld</td></tr>\n", rightclass, total);
}

static void print_authors(struct string_list *authors, int max_rows,
			  const struct string_list *labels)
{
	struct string_list_item *author, *bucket;
	struct authorstat *stats;
	size_t i, column, rows;
	long total;

	html("<table class='stats'>\n<tr><th>Author</th>");
	for (column = 0; column < labels->nr; column++)
		htmlf("<th>%s</th>", labels->items[column].string);
	html("<th>Total</th></tr>\n");

	// The row count arrives through ofs, which carries -1 for "all".
	rows = (max_rows <= 0 || (size_t)max_rows > authors->nr)
		? authors->nr : (size_t)max_rows;

	for (i = 0; i < rows; i++) {
		author = &authors->items[i];
		html("<tr><td class='left'>");
		html_txt(author->string);
		html("</td>");
		stats = author->util;
		total = 0;
		for (column = 0; column < labels->nr; column++) {
			const char *label = labels->items[column].string;

			bucket = string_list_lookup(&stats->periods, label);
			if (!bucket)
				html("<td>0</td>");
			else {
				htmlf("<td>%lu</td>", (uintptr_t)bucket->util);
				total += (uintptr_t)bucket->util;
			}
		}
		htmlf("<td class='sum'>%ld</td></tr>\n", total);
	}

	if (rows < authors->nr)
		print_summary_row(authors, rows, authors->nr - rows,
			"Others (%ld)", "left", "", "sum", labels);

	print_summary_row(authors, 0, authors->nr, "Total",
		"total", "sum", "sum", labels);
	html("</table>\n");
}

static void print_options_form(const struct cgit_period *period, int top)
{
	int choices, i;

	html("<div class='cgit-panel'>\n");
	html("<strong>stat options</strong>");
	html("<form method='get'>");
	cgit_add_hidden_formfields(1, 0, "stats");
	html("<table><tr><td colspan='2'></td></tr>\n");
	if (ctx.repo->max_stats > 1) {
		choices = ctx.repo->max_stats;
		html("<tr><td class='label'>Period:</td>");
		html("<td class='ctrl'><select name='period' data-autosubmit='1'>");
		for (i = 0; i < choices; i++)
			html_option(cgit_fmt("%c", periods[i].code),
				    periods[i].name,
				    cgit_fmt("%c", period->code));
		html("</select></td></tr>\n");
	}
	html("<tr><td class='label'>Authors:</td>");
	html("<td class='ctrl'><select name='ofs' data-autosubmit='1'>");
	html_intoption(10, "10", top);
	html_intoption(25, "25", top);
	html_intoption(50, "50", top);
	html_intoption(100, "100", top);
	html_intoption(-1, "all", top);
	html("</select></td></tr>\n");
	html("<tr><td></td><td class='ctrl'>");
	html("<noscript><input type='submit' value='Reload'></noscript>");
	html("</td></tr></table>");
	html("</form>\n");
	html("</div>\n");
}

int cgit_find_stats_period(const char *expr, const struct cgit_period **period)
{
	size_t i;
	char code = '\0';

	if (!expr)
		return 0;

	if (strlen(expr) == 1)
		code = expr[0];

	for (i = 0; i < ARRAY_SIZE(periods); i++)
		if (periods[i].code == code || !strcmp(periods[i].name, expr)) {
			if (period)
				*period = &periods[i];
			return i + 1;
		}
	return 0;
}

const char *cgit_find_stats_periodname(int idx)
{
	if (idx > 0 && idx <= (int)ARRAY_SIZE(periods))
		return periods[idx - 1].name;
	else
		return "";
}

void cgit_show_stats(void)
{
	struct string_list authors, labels;
	const struct cgit_period *period;
	int top, period_index;
	const char *code = "w";

	if (ctx.qry.period)
		code = ctx.qry.period;

	period_index = cgit_find_stats_period(code, &period);
	if (!period_index) {
		cgit_print_error_page(404, "Not Found",
			"Unknown statistics type: %c", code[0]);
		return;
	}
	if (period_index > ctx.repo->max_stats) {
		cgit_print_error_page(400, "Bad Request",
			"Statistics type disabled: %s", period->name);
		return;
	}
	authors = collect_stats(period);
	qsort(authors.items, authors.nr, sizeof(struct string_list_item),
		cmp_total_commits);

	top = ctx.qry.ofs;
	if (!top)
		top = DEFAULT_AUTHOR_ROWS;

	cgit_print_layout_start();
	print_options_form(period, top);

	htmlf("<h2>Commits per author per %s", period->name);
	if (ctx.qry.path) {
		html(" (path '");
		html_txt(ctx.qry.path);
		html("')");
	}
	html("</h2>\n");

	labels = build_period_labels(period);
	print_authors(&authors, top, &labels);
	string_list_clear(&labels, 0);

	cgit_print_layout_end();
}