stagit-fork

static git page generator - fork with some customisations
git clone https://git.ortlepp.eu/stagit-fork.git/
Log | Files | Refs | README | LICENSE

stagit.c (32149B)


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