stagit-gopher

static git page generator for gopher (mirror)
git clone git://git.2f30.org/stagit-gopher.git
Log | Files | Refs | README | LICENSE

stagit-gopher.c (31767B)


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