stagit

my branch of stagit
git clone git://git.hazbo.co.uk/stagit.git
Log | Files | Refs | README | LICENSE

stagit.c (31632B)


      1 #include <sys/stat.h>
      2 #include <sys/types.h>
      3 
      4 #include <err.h>
      5 #include <errno.h>
      6 #include <inttypes.h>
      7 #include <libgen.h>
      8 #include <limits.h>
      9 #include <stdio.h>
     10 #include <stdlib.h>
     11 #include <string.h>
     12 #include <unistd.h>
     13 
     14 #include <git2.h>
     15 
     16 #include "compat.h"
     17 
     18 struct deltainfo {
     19 	git_patch *patch;
     20 
     21 	size_t addcount;
     22 	size_t delcount;
     23 };
     24 
     25 struct commitinfo {
     26 	const git_oid *id;
     27 
     28 	char oid[GIT_OID_HEXSZ + 1];
     29 	char parentoid[GIT_OID_HEXSZ + 1];
     30 
     31 	const git_signature *author;
     32 	const git_signature *committer;
     33 	const char          *summary;
     34 	const char          *msg;
     35 
     36 	git_diff   *diff;
     37 	git_commit *commit;
     38 	git_commit *parent;
     39 	git_tree   *commit_tree;
     40 	git_tree   *parent_tree;
     41 
     42 	size_t addcount;
     43 	size_t delcount;
     44 	size_t filecount;
     45 
     46 	struct deltainfo **deltas;
     47 	size_t ndeltas;
     48 };
     49 
     50 static git_repository *repo;
     51 
     52 static const char *relpath = "";
     53 static const char *repodir;
     54 
     55 static char *name = "";
     56 static char *strippedname = "";
     57 static char description[255];
     58 static char cloneurl[1024];
     59 static char *submodules;
     60 static char *licensefiles[] = { "HEAD:LICENSE", "HEAD:LICENSE.md", "HEAD:COPYING" };
     61 static char *license;
     62 static char *readmefiles[] = { "HEAD:README", "HEAD:README.md" };
     63 static char *readme;
     64 static long long nlogcommits = -1; /* < 0 indicates not used */
     65 
     66 /* cache */
     67 static git_oid lastoid;
     68 static char lastoidstr[GIT_OID_HEXSZ + 2]; /* id + newline + NUL byte */
     69 static FILE *rcachefp, *wcachefp;
     70 static const char *cachefile;
     71 
     72 void
     73 joinpath(char *buf, size_t bufsiz, const char *path, const char *path2)
     74 {
     75 	int r;
     76 
     77 	r = snprintf(buf, bufsiz, "%s%s%s",
     78 		path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2);
     79 	if (r == -1 || (size_t)r >= bufsiz)
     80 		errx(1, "path truncated: '%s%s%s'",
     81 			path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2);
     82 }
     83 
     84 void
     85 deltainfo_free(struct deltainfo *di)
     86 {
     87 	if (!di)
     88 		return;
     89 	git_patch_free(di->patch);
     90 	memset(di, 0, sizeof(*di));
     91 	free(di);
     92 }
     93 
     94 int
     95 commitinfo_getstats(struct commitinfo *ci)
     96 {
     97 	struct deltainfo *di;
     98 	git_diff_options opts;
     99 	git_diff_find_options fopts;
    100 	const git_diff_delta *delta;
    101 	const git_diff_hunk *hunk;
    102 	const git_diff_line *line;
    103 	git_patch *patch = NULL;
    104 	size_t ndeltas, nhunks, nhunklines;
    105 	size_t i, j, k;
    106 
    107 	if (git_tree_lookup(&(ci->commit_tree), repo, git_commit_tree_id(ci->commit)))
    108 		goto err;
    109 	if (!git_commit_parent(&(ci->parent), ci->commit, 0)) {
    110 		if (git_tree_lookup(&(ci->parent_tree), repo, git_commit_tree_id(ci->parent))) {
    111 			ci->parent = NULL;
    112 			ci->parent_tree = NULL;
    113 		}
    114 	}
    115 
    116 	git_diff_init_options(&opts, GIT_DIFF_OPTIONS_VERSION);
    117 	opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH |
    118 	              GIT_DIFF_IGNORE_SUBMODULES |
    119 		      GIT_DIFF_INCLUDE_TYPECHANGE;
    120 	if (git_diff_tree_to_tree(&(ci->diff), repo, ci->parent_tree, ci->commit_tree, &opts))
    121 		goto err;
    122 
    123 	if (git_diff_find_init_options(&fopts, GIT_DIFF_FIND_OPTIONS_VERSION))
    124 		goto err;
    125 	/* find renames and copies, exact matches (no heuristic) for renames. */
    126 	fopts.flags |= GIT_DIFF_FIND_RENAMES | GIT_DIFF_FIND_COPIES |
    127 	               GIT_DIFF_FIND_EXACT_MATCH_ONLY;
    128 	if (git_diff_find_similar(ci->diff, &fopts))
    129 		goto err;
    130 
    131 	ndeltas = git_diff_num_deltas(ci->diff);
    132 	if (ndeltas && !(ci->deltas = calloc(ndeltas, sizeof(struct deltainfo *))))
    133 		err(1, "calloc");
    134 
    135 	for (i = 0; i < ndeltas; i++) {
    136 		if (git_patch_from_diff(&patch, ci->diff, i))
    137 			goto err;
    138 
    139 		if (!(di = calloc(1, sizeof(struct deltainfo))))
    140 			err(1, "calloc");
    141 		di->patch = patch;
    142 		ci->deltas[i] = di;
    143 
    144 		delta = git_patch_get_delta(patch);
    145 
    146 		/* skip stats for binary data */
    147 		if (delta->flags & GIT_DIFF_FLAG_BINARY)
    148 			continue;
    149 
    150 		nhunks = git_patch_num_hunks(patch);
    151 		for (j = 0; j < nhunks; j++) {
    152 			if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
    153 				break;
    154 			for (k = 0; ; k++) {
    155 				if (git_patch_get_line_in_hunk(&line, patch, j, k))
    156 					break;
    157 				if (line->old_lineno == -1) {
    158 					di->addcount++;
    159 					ci->addcount++;
    160 				} else if (line->new_lineno == -1) {
    161 					di->delcount++;
    162 					ci->delcount++;
    163 				}
    164 			}
    165 		}
    166 	}
    167 	ci->ndeltas = i;
    168 	ci->filecount = i;
    169 
    170 	return 0;
    171 
    172 err:
    173 	git_diff_free(ci->diff);
    174 	ci->diff = NULL;
    175 	git_tree_free(ci->commit_tree);
    176 	ci->commit_tree = NULL;
    177 	git_tree_free(ci->parent_tree);
    178 	ci->parent_tree = NULL;
    179 	git_commit_free(ci->parent);
    180 	ci->parent = NULL;
    181 
    182 	if (ci->deltas)
    183 		for (i = 0; i < ci->ndeltas; i++)
    184 			deltainfo_free(ci->deltas[i]);
    185 	free(ci->deltas);
    186 	ci->deltas = NULL;
    187 	ci->ndeltas = 0;
    188 	ci->addcount = 0;
    189 	ci->delcount = 0;
    190 	ci->filecount = 0;
    191 
    192 	return -1;
    193 }
    194 
    195 void
    196 commitinfo_free(struct commitinfo *ci)
    197 {
    198 	size_t i;
    199 
    200 	if (!ci)
    201 		return;
    202 	if (ci->deltas)
    203 		for (i = 0; i < ci->ndeltas; i++)
    204 			deltainfo_free(ci->deltas[i]);
    205 
    206 	free(ci->deltas);
    207 	git_diff_free(ci->diff);
    208 	git_tree_free(ci->commit_tree);
    209 	git_tree_free(ci->parent_tree);
    210 	git_commit_free(ci->commit);
    211 	git_commit_free(ci->parent);
    212 	memset(ci, 0, sizeof(*ci));
    213 	free(ci);
    214 }
    215 
    216 struct commitinfo *
    217 commitinfo_getbyoid(const git_oid *id)
    218 {
    219 	struct commitinfo *ci;
    220 
    221 	if (!(ci = calloc(1, sizeof(struct commitinfo))))
    222 		err(1, "calloc");
    223 
    224 	if (git_commit_lookup(&(ci->commit), repo, id))
    225 		goto err;
    226 	ci->id = id;
    227 
    228 	git_oid_tostr(ci->oid, sizeof(ci->oid), git_commit_id(ci->commit));
    229 	git_oid_tostr(ci->parentoid, sizeof(ci->parentoid), git_commit_parent_id(ci->commit, 0));
    230 
    231 	ci->author = git_commit_author(ci->commit);
    232 	ci->committer = git_commit_committer(ci->commit);
    233 	ci->summary = git_commit_summary(ci->commit);
    234 	ci->msg = git_commit_message(ci->commit);
    235 
    236 	return ci;
    237 
    238 err:
    239 	commitinfo_free(ci);
    240 
    241 	return NULL;
    242 }
    243 
    244 FILE *
    245 efopen(const char *name, const char *flags)
    246 {
    247 	FILE *fp;
    248 
    249 	if (!(fp = fopen(name, flags)))
    250 		err(1, "fopen: '%s'", name);
    251 
    252 	return fp;
    253 }
    254 
    255 /* Escape characters below as HTML 2.0 / XML 1.0. */
    256 void
    257 xmlencode(FILE *fp, const char *s, size_t len)
    258 {
    259 	size_t i;
    260 
    261 	for (i = 0; *s && i < len; s++, i++) {
    262 		switch(*s) {
    263 		case '<':  fputs("&lt;",   fp); break;
    264 		case '>':  fputs("&gt;",   fp); break;
    265 		case '\'': fputs("&#39;",  fp); break;
    266 		case '&':  fputs("&amp;",  fp); break;
    267 		case '"':  fputs("&quot;", fp); break;
    268 		default:   fputc(*s, fp);
    269 		}
    270 	}
    271 }
    272 
    273 int
    274 mkdirp(const char *path)
    275 {
    276 	char tmp[PATH_MAX], *p;
    277 
    278 	if (strlcpy(tmp, path, sizeof(tmp)) >= sizeof(tmp))
    279 		errx(1, "path truncated: '%s'", path);
    280 	for (p = tmp + (tmp[0] == '/'); *p; p++) {
    281 		if (*p != '/')
    282 			continue;
    283 		*p = '\0';
    284 		if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
    285 			return -1;
    286 		*p = '/';
    287 	}
    288 	if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
    289 		return -1;
    290 	return 0;
    291 }
    292 
    293 void
    294 printtimez(FILE *fp, const git_time *intime)
    295 {
    296 	struct tm *intm;
    297 	time_t t;
    298 	char out[32];
    299 
    300 	t = (time_t)intime->time;
    301 	if (!(intm = gmtime(&t)))
    302 		return;
    303 	strftime(out, sizeof(out), "%Y-%m-%dT%H:%M:%SZ", intm);
    304 	fputs(out, fp);
    305 }
    306 
    307 void
    308 printtime(FILE *fp, const git_time *intime)
    309 {
    310 	struct tm *intm;
    311 	time_t t;
    312 	char out[32];
    313 
    314 	t = (time_t)intime->time + (intime->offset * 60);
    315 	if (!(intm = gmtime(&t)))
    316 		return;
    317 	strftime(out, sizeof(out), "%a, %e %b %Y %H:%M:%S", intm);
    318 	if (intime->offset < 0)
    319 		fprintf(fp, "%s -%02d%02d", out,
    320 		            -(intime->offset) / 60, -(intime->offset) % 60);
    321 	else
    322 		fprintf(fp, "%s +%02d%02d", out,
    323 		            intime->offset / 60, intime->offset % 60);
    324 }
    325 
    326 void
    327 printtimeshort(FILE *fp, const git_time *intime)
    328 {
    329 	struct tm *intm;
    330 	time_t t;
    331 	char out[32];
    332 
    333 	t = (time_t)intime->time;
    334 	if (!(intm = gmtime(&t)))
    335 		return;
    336 	strftime(out, sizeof(out), "%Y-%m-%d %H:%M", intm);
    337 	fputs(out, fp);
    338 }
    339 
    340 void
    341 writeheader(FILE *fp, const char *title)
    342 {
    343 	fputs("<!DOCTYPE html>\n"
    344 		"<html>\n<head>\n"
    345 		"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
    346 		"<title>", fp);
    347 	xmlencode(fp, title, strlen(title));
    348 	if (title[0] && strippedname[0])
    349 		fputs(" - ", fp);
    350 	xmlencode(fp, strippedname, strlen(strippedname));
    351 	if (description[0])
    352 		fputs(" - ", fp);
    353 	xmlencode(fp, description, strlen(description));
    354 	fprintf(fp, "</title>\n<link rel=\"icon\" type=\"image/png\" href=\"%sfavicon.png\" />\n", relpath);
    355 	fprintf(fp, "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"%s Atom Feed\" href=\"%satom.xml\" />\n",
    356 		name, relpath);
    357 	fprintf(fp, "<link rel=\"stylesheet\" type=\"text/css\" href=\"%sstyle.css\" />\n", relpath);
    358 	fputs("</head>\n<body>\n<table><tr><td>", fp);
    359 	fprintf(fp, "<a href=\"../%s\"><img src=\"%slogo.png\" alt=\"\" width=\"32\" height=\"32\" /></a>",
    360 	        relpath, relpath);
    361 	fputs("</td><td><h1>", fp);
    362 	xmlencode(fp, strippedname, strlen(strippedname));
    363 	fputs("</h1><span class=\"desc\">", fp);
    364 	xmlencode(fp, description, strlen(description));
    365 	fputs("</span></td></tr>", fp);
    366 	if (cloneurl[0]) {
    367 		fputs("<tr class=\"url\"><td></td><td>git clone <a href=\"", fp);
    368 		xmlencode(fp, cloneurl, strlen(cloneurl));
    369 		fputs("\">", fp);
    370 		xmlencode(fp, cloneurl, strlen(cloneurl));
    371 		fputs("</a></td></tr>", fp);
    372 	}
    373 	fputs("<tr><td></td><td>\n", fp);
    374 	fprintf(fp, "<a href=\"%slog.html\">Log</a> | ", relpath);
    375 	fprintf(fp, "<a href=\"%sfiles.html\">Files</a> | ", relpath);
    376 	fprintf(fp, "<a href=\"%srefs.html\">Refs</a>", relpath);
    377 	if (submodules)
    378 		fprintf(fp, " | <a href=\"%sfile/%s.html\">Submodules</a>",
    379 		        relpath, submodules);
    380 	if (readme)
    381 		fprintf(fp, " | <a href=\"%sfile/%s.html\">README</a>",
    382 		        relpath, readme);
    383 	if (license)
    384 		fprintf(fp, " | <a href=\"%sfile/%s.html\">LICENSE</a>",
    385 		        relpath, license);
    386 	fputs("</td></tr></table>\n<hr/>\n<div id=\"content\">\n", fp);
    387 }
    388 
    389 void
    390 writefooter(FILE *fp)
    391 {
    392 	fputs("</div>\n</body>\n</html>\n", fp);
    393 }
    394 
    395 int
    396 writeblobhtml(FILE *fp, const git_blob *blob)
    397 {
    398 	size_t n = 0, i, prev;
    399 	const char *nfmt = "<a href=\"#l%d\" class=\"line\" id=\"l%d\">%7d</a> ";
    400 	const char *s = git_blob_rawcontent(blob);
    401 	git_off_t len = git_blob_rawsize(blob);
    402 
    403 	fputs("<pre id=\"blob\">\n", fp);
    404 
    405 	if (len > 0) {
    406 		for (i = 0, prev = 0; i < (size_t)len; i++) {
    407 			if (s[i] != '\n')
    408 				continue;
    409 			n++;
    410 			fprintf(fp, nfmt, n, n, n);
    411 			xmlencode(fp, &s[prev], i - prev + 1);
    412 			prev = i + 1;
    413 		}
    414 		/* trailing data */
    415 		if ((len - prev) > 0) {
    416 			n++;
    417 			fprintf(fp, nfmt, n, n, n);
    418 			xmlencode(fp, &s[prev], len - prev);
    419 		}
    420 	}
    421 
    422 	fputs("</pre>\n", fp);
    423 
    424 	return n;
    425 }
    426 
    427 void
    428 printcommit(FILE *fp, struct commitinfo *ci)
    429 {
    430 	fprintf(fp, "<b>commit</b> <a href=\"%scommit/%s.html\">%s</a>\n",
    431 		relpath, ci->oid, ci->oid);
    432 
    433 	if (ci->parentoid[0])
    434 		fprintf(fp, "<b>parent</b> <a href=\"%scommit/%s.html\">%s</a>\n",
    435 			relpath, ci->parentoid, ci->parentoid);
    436 
    437 	if (ci->author) {
    438 		fputs("<b>Author:</b> ", fp);
    439 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    440 		fputs(" &lt;<a href=\"mailto:", fp);
    441 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    442 		fputs("\">", fp);
    443 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    444 		fputs("</a>&gt;\n<b>Date:</b>   ", fp);
    445 		printtime(fp, &(ci->author->when));
    446 		fputc('\n', fp);
    447 	}
    448 	if (ci->msg) {
    449 		fputc('\n', fp);
    450 		xmlencode(fp, ci->msg, strlen(ci->msg));
    451 		fputc('\n', fp);
    452 	}
    453 }
    454 
    455 void
    456 printshowfile(FILE *fp, struct commitinfo *ci)
    457 {
    458 	const git_diff_delta *delta;
    459 	const git_diff_hunk *hunk;
    460 	const git_diff_line *line;
    461 	git_patch *patch;
    462 	size_t nhunks, nhunklines, changed, add, del, total, i, j, k;
    463 	char linestr[80];
    464 	int c;
    465 
    466 	printcommit(fp, ci);
    467 
    468 	if (!ci->deltas)
    469 		return;
    470 
    471 	if (ci->filecount > 1000   ||
    472 	    ci->ndeltas   > 1000   ||
    473 	    ci->addcount  > 100000 ||
    474 	    ci->delcount  > 100000) {
    475 		fputs("Diff is too large, output suppressed.\n", fp);
    476 		return;
    477 	}
    478 
    479 	/* diff stat */
    480 	fputs("<b>Diffstat:</b>\n<table>", fp);
    481 	for (i = 0; i < ci->ndeltas; i++) {
    482 		delta = git_patch_get_delta(ci->deltas[i]->patch);
    483 
    484 		switch (delta->status) {
    485 		case GIT_DELTA_ADDED:      c = 'A'; break;
    486 		case GIT_DELTA_COPIED:     c = 'C'; break;
    487 		case GIT_DELTA_DELETED:    c = 'D'; break;
    488 		case GIT_DELTA_MODIFIED:   c = 'M'; break;
    489 		case GIT_DELTA_RENAMED:    c = 'R'; break;
    490 		case GIT_DELTA_TYPECHANGE: c = 'T'; break;
    491 		default:                   c = ' '; break;
    492 		}
    493 		if (c == ' ')
    494 			fprintf(fp, "<tr><td>%c", c);
    495 		else
    496 			fprintf(fp, "<tr><td class=\"%c\">%c", c, c);
    497 
    498 		fprintf(fp, "</td><td><a href=\"#h%zu\">", i);
    499 		xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
    500 		if (strcmp(delta->old_file.path, delta->new_file.path)) {
    501 			fputs(" -&gt; ", fp);
    502 			xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
    503 		}
    504 
    505 		add = ci->deltas[i]->addcount;
    506 		del = ci->deltas[i]->delcount;
    507 		changed = add + del;
    508 		total = sizeof(linestr) - 2;
    509 		if (changed > total) {
    510 			if (add)
    511 				add = ((float)total / changed * add) + 1;
    512 			if (del)
    513 				del = ((float)total / changed * del) + 1;
    514 		}
    515 		memset(&linestr, '+', add);
    516 		memset(&linestr[add], '-', del);
    517 
    518 		fprintf(fp, "</a></td><td> | </td><td class=\"num\">%zu</td><td><span class=\"i\">",
    519 		        ci->deltas[i]->addcount + ci->deltas[i]->delcount);
    520 		fwrite(&linestr, 1, add, fp);
    521 		fputs("</span><span class=\"d\">", fp);
    522 		fwrite(&linestr[add], 1, del, fp);
    523 		fputs("</span></td></tr>\n", fp);
    524 	}
    525 	fprintf(fp, "</table></pre><pre>%zu file%s changed, %zu insertion%s(+), %zu deletion%s(-)\n",
    526 		ci->filecount, ci->filecount == 1 ? "" : "s",
    527 	        ci->addcount,  ci->addcount  == 1 ? "" : "s",
    528 	        ci->delcount,  ci->delcount  == 1 ? "" : "s");
    529 
    530 	fputs("<hr/>", fp);
    531 
    532 	for (i = 0; i < ci->ndeltas; i++) {
    533 		patch = ci->deltas[i]->patch;
    534 		delta = git_patch_get_delta(patch);
    535 		fprintf(fp, "<b>diff --git a/<a id=\"h%zu\" href=\"%sfile/%s.html\">%s</a> b/<a href=\"%sfile/%s.html\">%s</a></b>\n",
    536 			i, relpath, delta->old_file.path, delta->old_file.path,
    537 			relpath, delta->new_file.path, delta->new_file.path);
    538 
    539 		/* check binary data */
    540 		if (delta->flags & GIT_DIFF_FLAG_BINARY) {
    541 			fputs("Binary files differ.\n", fp);
    542 			continue;
    543 		}
    544 
    545 		nhunks = git_patch_num_hunks(patch);
    546 		for (j = 0; j < nhunks; j++) {
    547 			if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
    548 				break;
    549 
    550 			fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"h\">", i, j, i, j);
    551 			xmlencode(fp, hunk->header, hunk->header_len);
    552 			fputs("</a>", fp);
    553 
    554 			for (k = 0; ; k++) {
    555 				if (git_patch_get_line_in_hunk(&line, patch, j, k))
    556 					break;
    557 				if (line->old_lineno == -1)
    558 					fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"i\">+",
    559 						i, j, k, i, j, k);
    560 				else if (line->new_lineno == -1)
    561 					fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"d\">-",
    562 						i, j, k, i, j, k);
    563 				else
    564 					fputc(' ', fp);
    565 				xmlencode(fp, line->content, line->content_len);
    566 				if (line->old_lineno == -1 || line->new_lineno == -1)
    567 					fputs("</a>", fp);
    568 			}
    569 		}
    570 	}
    571 }
    572 
    573 void
    574 writelogline(FILE *fp, struct commitinfo *ci)
    575 {
    576 	fputs("<tr><td>", fp);
    577 	if (ci->author)
    578 		printtimeshort(fp, &(ci->author->when));
    579 	fputs("</td><td>", fp);
    580 	if (ci->summary) {
    581 		fprintf(fp, "<a href=\"%scommit/%s.html\">", relpath, ci->oid);
    582 		xmlencode(fp, ci->summary, strlen(ci->summary));
    583 		fputs("</a>", fp);
    584 	}
    585 	fputs("</td><td>", fp);
    586 	if (ci->author)
    587 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    588 	fputs("</td><td class=\"num\" align=\"right\">", fp);
    589 	fprintf(fp, "%zu", ci->filecount);
    590 	fputs("</td><td class=\"num\" align=\"right\">", fp);
    591 	fprintf(fp, "+%zu", ci->addcount);
    592 	fputs("</td><td class=\"num\" align=\"right\">", fp);
    593 	fprintf(fp, "-%zu", ci->delcount);
    594 	fputs("</td></tr>\n", fp);
    595 }
    596 
    597 int
    598 writelog(FILE *fp, const git_oid *oid)
    599 {
    600 	struct commitinfo *ci;
    601 	git_revwalk *w = NULL;
    602 	git_oid id;
    603 	char path[PATH_MAX], oidstr[GIT_OID_HEXSZ + 1];
    604 	FILE *fpfile;
    605 	int r;
    606 
    607 	git_revwalk_new(&w, repo);
    608 	git_revwalk_push(w, oid);
    609 	git_revwalk_simplify_first_parent(w);
    610 
    611 	while (!git_revwalk_next(&id, w)) {
    612 		relpath = "";
    613 
    614 		if (cachefile && !memcmp(&id, &lastoid, sizeof(id)))
    615 			break;
    616 
    617 		git_oid_tostr(oidstr, sizeof(oidstr), &id);
    618 		r = snprintf(path, sizeof(path), "commit/%s.html", oidstr);
    619 		if (r == -1 || (size_t)r >= sizeof(path))
    620 			errx(1, "path truncated: 'commit/%s.html'", oidstr);
    621 		r = access(path, F_OK);
    622 
    623 		/* optimization: if there are no log lines to write and
    624 		   the commit file already exists: skip the diffstat */
    625 		if (!nlogcommits && !r)
    626 			continue;
    627 
    628 		if (!(ci = commitinfo_getbyoid(&id)))
    629 			break;
    630 		/* diffstat: for stagit HTML required for the log.html line */
    631 		if (commitinfo_getstats(ci) == -1)
    632 			goto err;
    633 
    634 		if (nlogcommits < 0) {
    635 			writelogline(fp, ci);
    636 		} else if (nlogcommits > 0) {
    637 			writelogline(fp, ci);
    638 			nlogcommits--;
    639 			if (!nlogcommits && ci->parentoid[0])
    640 				fputs("<tr><td></td><td colspan=\"5\">"
    641 				      "More commits remaining [...]</td>"
    642 				      "</tr>\n", fp);
    643 		}
    644 
    645 		if (cachefile)
    646 			writelogline(wcachefp, ci);
    647 
    648 		/* check if file exists if so skip it */
    649 		if (r) {
    650 			relpath = "../";
    651 			fpfile = efopen(path, "w");
    652 			writeheader(fpfile, ci->summary);
    653 			fputs("<pre>", fpfile);
    654 			printshowfile(fpfile, ci);
    655 			fputs("</pre>\n", fpfile);
    656 			writefooter(fpfile);
    657 			fclose(fpfile);
    658 		}
    659 err:
    660 		commitinfo_free(ci);
    661 	}
    662 	git_revwalk_free(w);
    663 
    664 	relpath = "";
    665 
    666 	return 0;
    667 }
    668 
    669 void
    670 printcommitatom(FILE *fp, struct commitinfo *ci)
    671 {
    672 	fputs("<entry>\n", fp);
    673 
    674 	fprintf(fp, "<id>%s</id>\n", ci->oid);
    675 	if (ci->author) {
    676 		fputs("<published>", fp);
    677 		printtimez(fp, &(ci->author->when));
    678 		fputs("</published>\n", fp);
    679 	}
    680 	if (ci->committer) {
    681 		fputs("<updated>", fp);
    682 		printtimez(fp, &(ci->committer->when));
    683 		fputs("</updated>\n", fp);
    684 	}
    685 	if (ci->summary) {
    686 		fputs("<title type=\"text\">", fp);
    687 		xmlencode(fp, ci->summary, strlen(ci->summary));
    688 		fputs("</title>\n", fp);
    689 	}
    690 	fprintf(fp, "<link rel=\"alternate\" type=\"text/html\" href=\"commit/%s.html\" />",
    691 	        ci->oid);
    692 
    693 	if (ci->author) {
    694 		fputs("<author><name>", fp);
    695 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    696 		fputs("</name>\n<email>", fp);
    697 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    698 		fputs("</email>\n</author>\n", fp);
    699 	}
    700 
    701 	fputs("<content type=\"text\">", fp);
    702 	fprintf(fp, "commit %s\n", ci->oid);
    703 	if (ci->parentoid[0])
    704 		fprintf(fp, "parent %s\n", ci->parentoid);
    705 	if (ci->author) {
    706 		fputs("Author: ", fp);
    707 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    708 		fputs(" &lt;", fp);
    709 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    710 		fputs("&gt;\nDate:   ", fp);
    711 		printtime(fp, &(ci->author->when));
    712 		fputc('\n', fp);
    713 	}
    714 	if (ci->msg) {
    715 		fputc('\n', fp);
    716 		xmlencode(fp, ci->msg, strlen(ci->msg));
    717 	}
    718 	fputs("\n</content>\n</entry>\n", fp);
    719 }
    720 
    721 int
    722 writeatom(FILE *fp)
    723 {
    724 	struct commitinfo *ci;
    725 	git_revwalk *w = NULL;
    726 	git_oid id;
    727 	size_t i, m = 100; /* last 'm' commits */
    728 
    729 	fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    730 	      "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n<title>", fp);
    731 	xmlencode(fp, strippedname, strlen(strippedname));
    732 	fputs(", branch HEAD</title>\n<subtitle>", fp);
    733 	xmlencode(fp, description, strlen(description));
    734 	fputs("</subtitle>\n", fp);
    735 
    736 	git_revwalk_new(&w, repo);
    737 	git_revwalk_push_head(w);
    738 	git_revwalk_simplify_first_parent(w);
    739 
    740 	for (i = 0; i < m && !git_revwalk_next(&id, w); i++) {
    741 		if (!(ci = commitinfo_getbyoid(&id)))
    742 			break;
    743 		printcommitatom(fp, ci);
    744 		commitinfo_free(ci);
    745 	}
    746 	git_revwalk_free(w);
    747 
    748 	fputs("</feed>\n", fp);
    749 
    750 	return 0;
    751 }
    752 
    753 int
    754 writeblob(git_object *obj, const char *fpath, const char *filename, git_off_t filesize)
    755 {
    756 	char tmp[PATH_MAX] = "", *d;
    757 	const char *p;
    758 	int lc = 0;
    759 	FILE *fp;
    760 
    761 	if (strlcpy(tmp, fpath, sizeof(tmp)) >= sizeof(tmp))
    762 		errx(1, "path truncated: '%s'", fpath);
    763 	if (!(d = dirname(tmp)))
    764 		err(1, "dirname");
    765 	if (mkdirp(d))
    766 		return -1;
    767 
    768 	for (p = fpath, tmp[0] = '\0'; *p; p++) {
    769 		if (*p == '/' && strlcat(tmp, "../", sizeof(tmp)) >= sizeof(tmp))
    770 			errx(1, "path truncated: '../%s'", tmp);
    771 	}
    772 	relpath = tmp;
    773 
    774 	fp = efopen(fpath, "w");
    775 	writeheader(fp, filename);
    776 	fputs("<p> ", fp);
    777 	xmlencode(fp, filename, strlen(filename));
    778 	fprintf(fp, " (%juB)", (uintmax_t)filesize);
    779 	fputs("</p><hr/>", fp);
    780 
    781 	if (git_blob_is_binary((git_blob *)obj)) {
    782 		fputs("<p>Binary file.</p>\n", fp);
    783 	} else {
    784 		lc = writeblobhtml(fp, (git_blob *)obj);
    785 		if (ferror(fp))
    786 			err(1, "fwrite");
    787 	}
    788 	writefooter(fp);
    789 	fclose(fp);
    790 
    791 	relpath = "";
    792 
    793 	return lc;
    794 }
    795 
    796 const char *
    797 filemode(git_filemode_t m)
    798 {
    799 	static char mode[11];
    800 
    801 	memset(mode, '-', sizeof(mode) - 1);
    802 	mode[10] = '\0';
    803 
    804 	if (S_ISREG(m))
    805 		mode[0] = '-';
    806 	else if (S_ISBLK(m))
    807 		mode[0] = 'b';
    808 	else if (S_ISCHR(m))
    809 		mode[0] = 'c';
    810 	else if (S_ISDIR(m))
    811 		mode[0] = 'd';
    812 	else if (S_ISFIFO(m))
    813 		mode[0] = 'p';
    814 	else if (S_ISLNK(m))
    815 		mode[0] = 'l';
    816 	else if (S_ISSOCK(m))
    817 		mode[0] = 's';
    818 	else
    819 		mode[0] = '?';
    820 
    821 	if (m & S_IRUSR) mode[1] = 'r';
    822 	if (m & S_IWUSR) mode[2] = 'w';
    823 	if (m & S_IXUSR) mode[3] = 'x';
    824 	if (m & S_IRGRP) mode[4] = 'r';
    825 	if (m & S_IWGRP) mode[5] = 'w';
    826 	if (m & S_IXGRP) mode[6] = 'x';
    827 	if (m & S_IROTH) mode[7] = 'r';
    828 	if (m & S_IWOTH) mode[8] = 'w';
    829 	if (m & S_IXOTH) mode[9] = 'x';
    830 
    831 	if (m & S_ISUID) mode[3] = (mode[3] == 'x') ? 's' : 'S';
    832 	if (m & S_ISGID) mode[6] = (mode[6] == 'x') ? 's' : 'S';
    833 	if (m & S_ISVTX) mode[9] = (mode[9] == 'x') ? 't' : 'T';
    834 
    835 	return mode;
    836 }
    837 
    838 int
    839 writefilestree(FILE *fp, git_tree *tree, const char *path)
    840 {
    841 	const git_tree_entry *entry = NULL;
    842 	git_submodule *module = NULL;
    843 	git_object *obj = NULL;
    844 	git_off_t filesize;
    845 	const char *entryname;
    846 	char filepath[PATH_MAX], entrypath[PATH_MAX];
    847 	size_t count, i;
    848 	int lc, r, ret;
    849 
    850 	count = git_tree_entrycount(tree);
    851 	for (i = 0; i < count; i++) {
    852 		if (!(entry = git_tree_entry_byindex(tree, i)) ||
    853 		    !(entryname = git_tree_entry_name(entry)))
    854 			return -1;
    855 		joinpath(entrypath, sizeof(entrypath), path, entryname);
    856 
    857 		r = snprintf(filepath, sizeof(filepath), "file/%s.html",
    858 		         entrypath);
    859 		if (r == -1 || (size_t)r >= sizeof(filepath))
    860 			errx(1, "path truncated: 'file/%s.html'", entrypath);
    861 
    862 		if (!git_tree_entry_to_object(&obj, repo, entry)) {
    863 			switch (git_object_type(obj)) {
    864 			case GIT_OBJ_BLOB:
    865 				break;
    866 			case GIT_OBJ_TREE:
    867 				/* NOTE: recurses */
    868 				ret = writefilestree(fp, (git_tree *)obj,
    869 				                     entrypath);
    870 				git_object_free(obj);
    871 				if (ret)
    872 					return ret;
    873 				continue;
    874 			default:
    875 				git_object_free(obj);
    876 				continue;
    877 			}
    878 
    879 			filesize = git_blob_rawsize((git_blob *)obj);
    880 			lc = writeblob(obj, filepath, entryname, filesize);
    881 
    882 			fputs("<tr><td>", fp);
    883 			fputs(filemode(git_tree_entry_filemode(entry)), fp);
    884 			fprintf(fp, "</td><td><a href=\"%s%s\">", relpath, filepath);
    885 			xmlencode(fp, entrypath, strlen(entrypath));
    886 			fputs("</a></td><td class=\"num\" align=\"right\">", fp);
    887 			if (lc > 0)
    888 				fprintf(fp, "%dL", lc);
    889 			else
    890 				fprintf(fp, "%juB", (uintmax_t)filesize);
    891 			fputs("</td></tr>\n", fp);
    892 			git_object_free(obj);
    893 		} else if (!git_submodule_lookup(&module, repo, entryname)) {
    894 			fprintf(fp, "<tr><td>m---------</td><td><a href=\"%sfile/.gitmodules.html\">",
    895 				relpath);
    896 			xmlencode(fp, entrypath, strlen(entrypath));
    897 			git_submodule_free(module);
    898 			fputs("</a></td><td class=\"num\" align=\"right\"></td></tr>\n", fp);
    899 		}
    900 	}
    901 
    902 	return 0;
    903 }
    904 
    905 int
    906 writefiles(FILE *fp, const git_oid *id)
    907 {
    908 	git_tree *tree = NULL;
    909 	git_commit *commit = NULL;
    910 	int ret = -1;
    911 
    912 	fputs("<table id=\"files\"><thead>\n<tr>"
    913 	      "<td><b>Mode</b></td><td><b>Name</b></td>"
    914 	      "<td class=\"num\" align=\"right\"><b>Size</b></td>"
    915 	      "</tr>\n</thead><tbody>\n", fp);
    916 
    917 	if (!git_commit_lookup(&commit, repo, id) &&
    918 	    !git_commit_tree(&tree, commit))
    919 		ret = writefilestree(fp, tree, "");
    920 
    921 	fputs("</tbody></table>", fp);
    922 
    923 	git_commit_free(commit);
    924 	git_tree_free(tree);
    925 
    926 	return ret;
    927 }
    928 
    929 int
    930 refs_cmp(const void *v1, const void *v2)
    931 {
    932 	git_reference *r1 = (*(git_reference **)v1);
    933 	git_reference *r2 = (*(git_reference **)v2);
    934 	int r;
    935 
    936 	if ((r = git_reference_is_branch(r1) - git_reference_is_branch(r2)))
    937 		return r;
    938 
    939 	return strcmp(git_reference_shorthand(r1),
    940 	              git_reference_shorthand(r2));
    941 }
    942 
    943 int
    944 writerefs(FILE *fp)
    945 {
    946 	struct commitinfo *ci;
    947 	const git_oid *id = NULL;
    948 	git_object *obj = NULL;
    949 	git_reference *dref = NULL, *r, *ref = NULL;
    950 	git_reference_iterator *it = NULL;
    951 	git_reference **refs = NULL;
    952 	size_t count, i, j, refcount;
    953 	const char *titles[] = { "Branches", "Tags" };
    954 	const char *ids[] = { "branches", "tags" };
    955 	const char *name;
    956 
    957 	if (git_reference_iterator_new(&it, repo))
    958 		return -1;
    959 
    960 	for (refcount = 0; !git_reference_next(&ref, it); refcount++) {
    961 		if (!(refs = reallocarray(refs, refcount + 1, sizeof(git_reference *))))
    962 			err(1, "realloc");
    963 		refs[refcount] = ref;
    964 	}
    965 	git_reference_iterator_free(it);
    966 
    967 	/* sort by type then shorthand name */
    968 	qsort(refs, refcount, sizeof(git_reference *), refs_cmp);
    969 
    970 	for (j = 0; j < 2; j++) {
    971 		for (i = 0, count = 0; i < refcount; i++) {
    972 			if (!(git_reference_is_branch(refs[i]) && j == 0) &&
    973 			    !(git_reference_is_tag(refs[i]) && j == 1))
    974 				continue;
    975 
    976 			switch (git_reference_type(refs[i])) {
    977 			case GIT_REF_SYMBOLIC:
    978 				if (git_reference_resolve(&dref, refs[i]))
    979 					goto err;
    980 				r = dref;
    981 				break;
    982 			case GIT_REF_OID:
    983 				r = refs[i];
    984 				break;
    985 			default:
    986 				continue;
    987 			}
    988 			if (!git_reference_target(r) ||
    989 			    git_reference_peel(&obj, r, GIT_OBJ_ANY))
    990 				goto err;
    991 			if (!(id = git_object_id(obj)))
    992 				goto err;
    993 			if (!(ci = commitinfo_getbyoid(id)))
    994 				break;
    995 
    996 			/* print header if it has an entry (first). */
    997 			if (++count == 1) {
    998 				fprintf(fp, "<h2>%s</h2><table id=\"%s\">"
    999 			                "<thead>\n<tr><td><b>Name</b></td>"
   1000 				        "<td><b>Last commit date</b></td>"
   1001 				        "<td><b>Author</b></td>\n</tr>\n"
   1002 				        "</thead><tbody>\n",
   1003 				         titles[j], ids[j]);
   1004 			}
   1005 
   1006 			relpath = "";
   1007 			name = git_reference_shorthand(r);
   1008 
   1009 			fputs("<tr><td>", fp);
   1010 			xmlencode(fp, name, strlen(name));
   1011 			fputs("</td><td>", fp);
   1012 			if (ci->author)
   1013 				printtimeshort(fp, &(ci->author->when));
   1014 			fputs("</td><td>", fp);
   1015 			if (ci->author)
   1016 				xmlencode(fp, ci->author->name, strlen(ci->author->name));
   1017 			fputs("</td></tr>\n", fp);
   1018 
   1019 			relpath = "../";
   1020 
   1021 			commitinfo_free(ci);
   1022 			git_object_free(obj);
   1023 			obj = NULL;
   1024 			git_reference_free(dref);
   1025 			dref = NULL;
   1026 		}
   1027 		/* table footer */
   1028 		if (count)
   1029 			fputs("</tbody></table><br/>", fp);
   1030 	}
   1031 
   1032 err:
   1033 	git_object_free(obj);
   1034 	git_reference_free(dref);
   1035 
   1036 	for (i = 0; i < refcount; i++)
   1037 		git_reference_free(refs[i]);
   1038 	free(refs);
   1039 
   1040 	return 0;
   1041 }
   1042 
   1043 void
   1044 usage(char *argv0)
   1045 {
   1046 	fprintf(stderr, "%s [-c cachefile | -l commits] repodir\n", argv0);
   1047 	exit(1);
   1048 }
   1049 
   1050 int
   1051 main(int argc, char *argv[])
   1052 {
   1053 	git_object *obj = NULL;
   1054 	const git_oid *head = NULL;
   1055 	mode_t mask;
   1056 	FILE *fp, *fpread;
   1057 	char path[PATH_MAX], repodirabs[PATH_MAX + 1], *p;
   1058 	char tmppath[64] = "cache.XXXXXXXXXXXX", buf[BUFSIZ];
   1059 	size_t n;
   1060 	int i, fd;
   1061 
   1062 	for (i = 1; i < argc; i++) {
   1063 		if (argv[i][0] != '-') {
   1064 			if (repodir)
   1065 				usage(argv[0]);
   1066 			repodir = argv[i];
   1067 		} else if (argv[i][1] == 'c') {
   1068 			if (nlogcommits > 0 || i + 1 >= argc)
   1069 				usage(argv[0]);
   1070 			cachefile = argv[++i];
   1071 		} else if (argv[i][1] == 'l') {
   1072 			if (cachefile || i + 1 >= argc)
   1073 				usage(argv[0]);
   1074 			errno = 0;
   1075 			nlogcommits = strtoll(argv[++i], &p, 10);
   1076 			if (argv[i][0] == '\0' || *p != '\0' ||
   1077 			    nlogcommits <= 0 || errno)
   1078 				usage(argv[0]);
   1079 		}
   1080 	}
   1081 	if (!repodir)
   1082 		usage(argv[0]);
   1083 
   1084 	if (!realpath(repodir, repodirabs))
   1085 		err(1, "realpath");
   1086 
   1087 	git_libgit2_init();
   1088 
   1089 #ifdef __OpenBSD__
   1090 	if (cachefile) {
   1091 		if (pledge("stdio rpath wpath cpath fattr", NULL) == -1)
   1092 			err(1, "pledge");
   1093 	} else {
   1094 		if (pledge("stdio rpath wpath cpath", NULL) == -1)
   1095 			err(1, "pledge");
   1096 	}
   1097 #endif
   1098 
   1099 	if (git_repository_open_ext(&repo, repodir,
   1100 		GIT_REPOSITORY_OPEN_NO_SEARCH, NULL) < 0) {
   1101 		fprintf(stderr, "%s: cannot open repository\n", argv[0]);
   1102 		return 1;
   1103 	}
   1104 
   1105 	/* find HEAD */
   1106 	if (!git_revparse_single(&obj, repo, "HEAD"))
   1107 		head = git_object_id(obj);
   1108 	git_object_free(obj);
   1109 
   1110 	/* use directory name as name */
   1111 	if ((name = strrchr(repodirabs, '/')))
   1112 		name++;
   1113 	else
   1114 		name = "";
   1115 
   1116 	/* strip .git suffix */
   1117 	if (!(strippedname = strdup(name)))
   1118 		err(1, "strdup");
   1119 	if ((p = strrchr(strippedname, '.')))
   1120 		if (!strcmp(p, ".git"))
   1121 			*p = '\0';
   1122 
   1123 	/* read description or .git/description */
   1124 	joinpath(path, sizeof(path), repodir, "description");
   1125 	if (!(fpread = fopen(path, "r"))) {
   1126 		joinpath(path, sizeof(path), repodir, ".git/description");
   1127 		fpread = fopen(path, "r");
   1128 	}
   1129 	if (fpread) {
   1130 		if (!fgets(description, sizeof(description), fpread))
   1131 			description[0] = '\0';
   1132 		fclose(fpread);
   1133 	}
   1134 
   1135 	/* read url or .git/url */
   1136 	joinpath(path, sizeof(path), repodir, "url");
   1137 	if (!(fpread = fopen(path, "r"))) {
   1138 		joinpath(path, sizeof(path), repodir, ".git/url");
   1139 		fpread = fopen(path, "r");
   1140 	}
   1141 	if (fpread) {
   1142 		if (!fgets(cloneurl, sizeof(cloneurl), fpread))
   1143 			cloneurl[0] = '\0';
   1144 		cloneurl[strcspn(cloneurl, "\n")] = '\0';
   1145 		fclose(fpread);
   1146 	}
   1147 
   1148 	/* check LICENSE */
   1149 	for (i = 0; i < sizeof(licensefiles) / sizeof(*licensefiles) && !license; i++) {
   1150 		if (!git_revparse_single(&obj, repo, licensefiles[i]) &&
   1151 		    git_object_type(obj) == GIT_OBJ_BLOB)
   1152 			license = licensefiles[i] + strlen("HEAD:");
   1153 		git_object_free(obj);
   1154 	}
   1155 
   1156 	/* check README */
   1157 	for (i = 0; i < sizeof(readmefiles) / sizeof(*readmefiles) && !readme; i++) {
   1158 		if (!git_revparse_single(&obj, repo, readmefiles[i]) &&
   1159 		    git_object_type(obj) == GIT_OBJ_BLOB)
   1160 			readme = readmefiles[i] + strlen("HEAD:");
   1161 		git_object_free(obj);
   1162 	}
   1163 
   1164 	if (!git_revparse_single(&obj, repo, "HEAD:.gitmodules") &&
   1165 	    git_object_type(obj) == GIT_OBJ_BLOB)
   1166 		submodules = ".gitmodules";
   1167 	git_object_free(obj);
   1168 
   1169 	/* log for HEAD */
   1170 	fp = efopen("log.html", "w");
   1171 	relpath = "";
   1172 	mkdir("commit", S_IRWXU | S_IRWXG | S_IRWXO);
   1173 	writeheader(fp, "Log");
   1174 	fputs("<table id=\"log\"><thead>\n<tr><td><b>Date</b></td>"
   1175 	      "<td><b>Commit message</b></td>"
   1176 	      "<td><b>Author</b></td><td class=\"num\" align=\"right\"><b>Files</b></td>"
   1177 	      "<td class=\"num\" align=\"right\"><b>+</b></td>"
   1178 	      "<td class=\"num\" align=\"right\"><b>-</b></td></tr>\n</thead><tbody>\n", fp);
   1179 
   1180 	if (cachefile && head) {
   1181 		/* read from cache file (does not need to exist) */
   1182 		if ((rcachefp = fopen(cachefile, "r"))) {
   1183 			if (!fgets(lastoidstr, sizeof(lastoidstr), rcachefp))
   1184 				errx(1, "%s: no object id", cachefile);
   1185 			if (git_oid_fromstr(&lastoid, lastoidstr))
   1186 				errx(1, "%s: invalid object id", cachefile);
   1187 		}
   1188 
   1189 		/* write log to (temporary) cache */
   1190 		if ((fd = mkstemp(tmppath)) == -1)
   1191 			err(1, "mkstemp");
   1192 		if (!(wcachefp = fdopen(fd, "w")))
   1193 			err(1, "fdopen: '%s'", tmppath);
   1194 		/* write last commit id (HEAD) */
   1195 		git_oid_tostr(buf, sizeof(buf), head);
   1196 		fprintf(wcachefp, "%s\n", buf);
   1197 
   1198 		writelog(fp, head);
   1199 
   1200 		if (rcachefp) {
   1201 			/* append previous log to log.html and the new cache */
   1202 			while (!feof(rcachefp)) {
   1203 				n = fread(buf, 1, sizeof(buf), rcachefp);
   1204 				if (ferror(rcachefp))
   1205 					err(1, "fread");
   1206 				if (fwrite(buf, 1, n, fp) != n ||
   1207 				    fwrite(buf, 1, n, wcachefp) != n)
   1208 					err(1, "fwrite");
   1209 			}
   1210 			fclose(rcachefp);
   1211 		}
   1212 		fclose(wcachefp);
   1213 	} else {
   1214 		if (head)
   1215 			writelog(fp, head);
   1216 	}
   1217 
   1218 	fputs("</tbody></table>", fp);
   1219 	writefooter(fp);
   1220 	fclose(fp);
   1221 
   1222 	/* files for HEAD */
   1223 	fp = efopen("files.html", "w");
   1224 	writeheader(fp, "Files");
   1225 	if (head)
   1226 		writefiles(fp, head);
   1227 	writefooter(fp);
   1228 	fclose(fp);
   1229 
   1230 	/* summary page with branches and tags */
   1231 	fp = efopen("refs.html", "w");
   1232 	writeheader(fp, "Refs");
   1233 	writerefs(fp);
   1234 	writefooter(fp);
   1235 	fclose(fp);
   1236 
   1237 	/* Atom feed */
   1238 	fp = efopen("atom.xml", "w");
   1239 	writeatom(fp);
   1240 	fclose(fp);
   1241 
   1242 	/* rename new cache file on success */
   1243 	if (cachefile && head) {
   1244 		if (rename(tmppath, cachefile))
   1245 			err(1, "rename: '%s' to '%s'", tmppath, cachefile);
   1246 		umask((mask = umask(0)));
   1247 		if (chmod(cachefile,
   1248 		    (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) & ~mask))
   1249 			err(1, "chmod: '%s'", cachefile);
   1250 	}
   1251 
   1252 	/* cleanup */
   1253 	git_repository_free(repo);
   1254 	git_libgit2_shutdown();
   1255 
   1256 	return 0;
   1257 }