blob: a7010d0af2d63759eba1a8bd7a58d5f4f2c78ec9 (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
/*
 * The blame page, which shows a file next to the commit that last touched
 * each of its lines. git returns blame as runs of neighbouring lines that
 * share a commit, and the page turns every run into one block in each column
 * so the hashes, the line numbers and the striped background all line up with
 * the source. Only a regular file can be blamed, so a path naming a folder is
 * turned away.
 */

#define USE_THE_REPOSITORY_VARIABLE

#include "cgit.h"
#include "filter.h"
#include "html.h"
#include "parsing.h"
#include "shared.h"
#include "ui-blame.h"
#include "ui-shared.h"

// A tab in the rendered source runs on to the next multiple of this. The
// stylesheet leaves tab-size alone, so the measurement has to match what the
// browser does on its own rather than anything cgit picks.
#define TAB_WIDTH 8

enum blame_target {
	TARGET_MISSING,
	TARGET_FILE,
	TARGET_FOLDER,
};

struct walk_tree_context {
	char *rev;
	int match_baselen;
	enum blame_target found;
};

// A commit that touched several separate parts of the file comes back once
// per part, and each repeat would parse the commit again, so the rendered
// detail is cached here and looked up by object id.
static struct string_list suspect_details = STRING_LIST_INIT_DUP;

static void free_suspect_details(void)
{
	struct string_list_item *item;

	for_each_string_list_item(item, &suspect_details)
		free(item->util);
	string_list_clear(&suspect_details, 0);
}

/*
 * The scoreboard keeps a pointer to revs, so the caller owns both and has to
 * keep them alive together.
 */
static void run_blame(struct blame_scoreboard *sb, struct rev_info *revs,
		      const char *path, const char *rev)
{
	struct strvec argv = STRVEC_INIT;
	struct blame_origin *origin;

	strvec_push(&argv, "blame");
	strvec_push(&argv, rev);
	repo_init_revisions(the_repository, revs, NULL);
	revs->diffopt.flags.allow_textconv = 1;
	setup_revisions(argv.nr, argv.v, revs, NULL);
	init_scoreboard(sb);
	sb->revs = revs;
	sb->repo = the_repository;
	sb->path = path;
	setup_scoreboard(sb, &origin);
	origin->suspects = blame_entry_prepend(NULL, 0, sb->num_lines, origin);
	prio_queue_put(&sb->commits, origin->commit);
	blame_origin_decref(origin);
	sb->ent = NULL;
	sb->path = path;
	assign_blame(sb, 0);
	blame_sort_final(sb);
	blame_coalesce(sb);
}

/*
 * A single blame entry can cover the whole file, so the run is handed on in
 * batches rather than built whole.
 */
static void emit_chars(char ch, unsigned long count)
{
	struct strbuf run = STRBUF_INIT;

	while (count) {
		unsigned long n = count < HTML_BATCH ? count : HTML_BATCH;

		strbuf_addchars(&run, ch, n);
		html_raw(run.buf, run.len);
		strbuf_reset(&run);
		count -= n;
	}
	strbuf_release(&run);
}

/*
 * The returned string belongs to suspect_details, not the caller.
 */
static char *suspect_detail(struct blame_origin *suspect)
{
	struct commitinfo *info;
	struct strbuf detail = STRBUF_INIT;
	struct string_list_item *cached;
	char key[GIT_MAX_HEXSZ + 1];

	// A private copy, since oid_to_hex hands back a buffer it reuses and
	// the commit parse below is free to call it again.
	oid_to_hex_r(key, &suspect->commit->object.oid);

	cached = string_list_lookup(&suspect_details, key);
	if (cached)
		return cached->util;

	info = cgit_parse_commit(suspect->commit);

	strbuf_addf(&detail, "author  %s", info->author);
	if (!ctx.cfg.noplainemail)
		strbuf_addf(&detail, " %s", info->author_email);
	strbuf_addf(&detail, "  %s\n",
		    show_date(info->author_date, info->author_tz,
				    cgit_date_mode(DATE_ISO8601)));

	strbuf_addf(&detail, "committer  %s", info->committer);
	if (!ctx.cfg.noplainemail)
		strbuf_addf(&detail, " %s", info->committer_email);
	strbuf_addf(&detail, "  %s\n\n",
		    show_date(info->committer_date, info->committer_tz,
				    cgit_date_mode(DATE_ISO8601)));

	strbuf_addstr(&detail, info->subject);

	cgit_free_commitinfo(info);
	cached = string_list_insert(&suspect_details, key);
	cached->util = strbuf_detach(&detail, NULL);
	return cached->util;
}

static void emit_entry_hash(struct blame_entry *ent)
{
	struct blame_origin *suspect = ent->suspect;
	struct object_id *oid = &suspect->commit->object.oid;
	const char *detail = suspect_detail(suspect);

	html("<span class='oid'>");
	cgit_commit_link(repo_find_unique_abbrev(the_repository, oid,
						 DEFAULT_ABBREV),
			 detail, NULL, ctx.qry.head, oid_to_hex(oid),
			 suspect->path);
	html("</span>");

	if (!repo_parse_commit(the_repository, suspect->commit) &&
	    suspect->commit->parents) {
		struct commit *parent = suspect->commit->parents->item;

		html(" ");
		cgit_blame_link("^", "Blame the previous revision", NULL,
				ctx.qry.head, oid_to_hex(&parent->object.oid),
				suspect->path);
	}

	// The stripes only line up across the columns if each column gives an
	// entry the same height, so pad out to the lines the entry covers.
	emit_chars('\n', ent->num_lines);
}

static void emit_hashes(struct blame_scoreboard *sb)
{
	struct blame_entry *ent;

	html("<td class='hashes'>");
	for (ent = sb->ent; ent; ent = ent->next) {
		html("<div class='alt'><pre>");
		emit_entry_hash(ent);
		html("</pre></div>");
	}
	html("</td>\n");
}

static void emit_entry_linenumbers(struct blame_entry *ent)
{
	const char *numberfmt = "<a id='n%1$d' href='#n%1$d'>%1$d</a>\n";
	struct strbuf numbers = STRBUF_INIT;
	int lineno = ent->lno;

	while (lineno < ent->lno + ent->num_lines) {
		strbuf_addf(&numbers, numberfmt, ++lineno);
		if (numbers.len >= HTML_BATCH) {
			html_raw(numbers.buf, numbers.len);
			strbuf_reset(&numbers);
		}
	}
	html_raw(numbers.buf, numbers.len);
	strbuf_release(&numbers);
}

static void emit_linenumbers(struct blame_scoreboard *sb)
{
	struct blame_entry *ent;

	html("<td class='linenumbers'>");
	for (ent = sb->ent; ent; ent = ent->next) {
		html("<div class='alt'><pre>");
		emit_entry_linenumbers(ent);
		html("</pre></div>");
	}
	html("</td>\n");
}

static size_t line_width(struct blame_scoreboard *sb, int line)
{
	const char *pos = blame_nth_line(sb, line);
	const char *end = blame_nth_line(sb, line + 1);
	size_t width = 0;

	while (pos < end) {
		width++;
		if (*pos++ == '\t')
			width = (width + TAB_WIDTH - 1) & ~(TAB_WIDTH - 1);
	}
	return width;
}

/*
 * The stylesheet takes the source pre out of flow and positions it over these
 * blocks, so nothing else gives the cell a size and each block has to be
 * padded to the height and the width of the lines it stands behind.
 */
static void emit_entry_background(struct blame_scoreboard *sb,
				  struct blame_entry *ent)
{
	size_t widest = 2;
	int line;

	for (line = ent->lno; line < ent->lno + ent->num_lines; line++) {
		size_t width = line_width(sb, line);

		if (width > widest)
			widest = width;
	}

	emit_chars('\n', ent->num_lines);
	emit_chars(' ', widest - 1);
}

/*
 * Frees each entry on the way past, so this has to be the last pass over the
 * scoreboard's entries.
 */
static void emit_line_backgrounds(struct blame_scoreboard *sb)
{
	struct blame_entry *ent = sb->ent;

	html("<div>");
	while (ent) {
		struct blame_entry *next = ent->next;

		html("<div class='alt'><pre>");
		emit_entry_background(sb, ent);
		html("</pre></div>");
		free(ent);
		ent = next;
	}
	html("</div>");
}

static void print_blame_page(const struct object_id *oid, const char *path,
			     const char *filename, const char *rev)
{
	enum object_type type;
	char *buf;
	unsigned long size;
	struct rev_info revs;
	struct blame_scoreboard sb;

	type = odb_read_object_info(the_repository->objects, oid, &size);
	if (type == OBJ_BAD) {
		cgit_print_error_page(404, "Not found", "Bad object name: %s",
				      oid_to_hex(oid));
		return;
	}
	if (ctx.cfg.max_blob_size && size / 1024 > (unsigned long)ctx.cfg.max_blob_size) {
		cgit_print_error_page(413, "Too large",
			"blob size (%luKB) exceeds display size limit (%dKB)",
			size / 1024, ctx.cfg.max_blob_size);
		return;
	}

	buf = odb_read_object(the_repository->objects, oid, &type, &size);
	if (!buf) {
		cgit_print_error_page(500, "Internal server error",
			"Error reading object %s", oid_to_hex(oid));
		return;
	}

	run_blame(&sb, &revs, path, rev);

	cgit_set_title_from_path(path);

	cgit_print_layout_start();
	htmlf("blob: %s (", oid_to_hex(oid));
	cgit_plain_link("plain", NULL, NULL, ctx.qry.head, rev, path);
	html(") (");
	cgit_tree_link("tree", NULL, NULL, ctx.qry.head, rev, path);
	html(")\n");

	// A NUL past the window buffer_is_binary sniffs would end html_txt
	// early while the hash and line number columns still cover the whole
	// file, so a blob holding one anywhere is treated as binary too.
	if (buffer_is_binary(buf, size) || memchr(buf, 0, size)) {
		struct blame_entry *ent = sb.ent, *next;

		// The scoreboard is normally consumed by the column passes,
		// so this early exit has to release it itself.
		for (; ent; ent = next) {
			next = ent->next;
			free(ent);
		}
		free((void *)sb.final_buf);
		html("<div class='error'>blob is binary.</div>");
		goto cleanup;
	}
	html("<table class='blame blob'>\n<tr>\n");

	emit_hashes(&sb);

	if (ctx.cfg.enable_tree_linenumbers)
		emit_linenumbers(&sb);

	html("<td class='lines'><div>");
	emit_line_backgrounds(&sb);

	free((void *)sb.final_buf);

	html("<pre><code>");
	if (ctx.repo->source_filter) {
		char *filter_arg = xstrdup(filename);
		cgit_open_filter(ctx.repo->source_filter, filter_arg);
		html_raw(buf, size);
		cgit_close_filter(ctx.repo->source_filter);
		free(filter_arg);
	} else {
		html_txt(buf);
	}
	html("</code></pre>");

	html("</div></td>\n");

	html("</tr>\n</table>\n");

cleanup:
	cgit_print_layout_end();
	free_suspect_details();
	free(buf);
}

static int walk_tree(const struct object_id *oid, struct strbuf *base,
		     const char *pathname, unsigned mode, void *data)
{
	struct walk_tree_context *walk = data;

	// match_baselen is -1 when no path was given, which no length equals.
	if (walk->match_baselen >= 0 &&
	    base->len == (size_t)walk->match_baselen) {
		if (S_ISREG(mode)) {
			struct strbuf fullpath = STRBUF_INIT;

			strbuf_addbuf(&fullpath, base);
			strbuf_addstr(&fullpath, pathname);
			print_blame_page(oid, fullpath.buf, pathname,
					 walk->rev);
			strbuf_release(&fullpath);
			walk->found = TARGET_FILE;
		} else if (S_ISDIR(mode)) {
			walk->found = TARGET_FOLDER;
		}
	} else if (base->len < INT_MAX
			&& (int)base->len > walk->match_baselen) {
		walk->found = TARGET_FOLDER;
	} else if (S_ISDIR(mode)) {
		return READ_TREE_RECURSIVE;
	}
	return 0;
}

static int basedir_len(const char *path)
{
	const char *slash = strrchr(path, '/');

	if (slash)
		return slash - path + 1;
	return 0;
}

void cgit_print_blame(void)
{
	const char *rev = ctx.qry.oid;
	struct object_id oid;
	struct commit *commit;
	int path_len = ctx.qry.path ? strlen(ctx.qry.path) : 0;
	// nowildcard_len matches len so git treats the path as literal rather
	// than as a glob, which is what a request naming one file means.
	struct pathspec_item path_items = {
		.match = ctx.qry.path,
		.len = path_len,
		.nowildcard_len = path_len
	};
	struct pathspec paths = {
		.nr = 1,
		.items = &path_items
	};
	struct walk_tree_context walk = {
		.found = TARGET_MISSING
	};

	if (!rev)
		rev = ctx.qry.head;

	if (repo_get_oid(the_repository, rev, &oid)) {
		cgit_print_error_page(404, "Not found",
			"Invalid revision name: %s", rev);
		return;
	}
	commit = lookup_commit_reference(the_repository, &oid);
	if (!commit || repo_parse_commit(the_repository, commit)) {
		cgit_print_error_page(404, "Not found",
			"Invalid commit reference: %s", rev);
		return;
	}

	walk.rev = xstrdup(rev);
	walk.match_baselen = path_items.match ?
			     basedir_len(path_items.match) : -1;

	read_tree(the_repository, repo_get_commit_tree(the_repository, commit),
		  &paths, walk_tree, &walk);
	if (walk.found == TARGET_MISSING)
		cgit_print_error_page(404, "Not found", "Not found");
	else if (walk.found == TARGET_FOLDER)
		cgit_print_error_page(404, "No blame for folders",
			"Blame is not available for folders.");

	free(walk.rev);
}