logo

stagit

STAtic GIT web view generator (in C)

stagit.c (32182B)


      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 #include "config.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 		"<title>", fp);
    348 	xmlencode(fp, title, strlen(title));
    349 	if (title[0] && strippedname[0])
    350 		fputs(" - ", fp);
    351 	xmlencode(fp, strippedname, strlen(strippedname));
    352 	if (description[0])
    353 		fputs(" - ", fp);
    354 	xmlencode(fp, description, strlen(description));
    355 	if(strlen(faviconurl) > 0) {
    356 		fprintf(fp, "</title>\n<link rel=\"icon\" type=\"image/png\" href=\"%s\" />\n", faviconurl);
    357 	}
    358 	fprintf(fp, "<link rel=\"stylesheet\" type=\"text/css\" href=\"%sstyle.css\" />\n", assetpath);
    359 	fputs("</head>\n<body>\n<header>", fp);
    360 	fprintf(fp, "<a href=\"..\"><img src=\"%slogo.png\" alt=\"logo\" width=\"32\" height=\"32\" /></a>",
    361 	        assetpath);
    362 	fputs("<h1>", fp);
    363 	xmlencode(fp, strippedname, strlen(strippedname));
    364 	fputs("</h1><span class=\"desc\">", fp);
    365 	xmlencode(fp, description, strlen(description));
    366 	fputs("</span>", fp);
    367 	if (cloneurl[0]) {
    368 		fputs("<code class=\"url\"><td></td><td>git clone <a rel=\"vcs-git\" href=\"", fp);
    369 		xmlencode(fp, cloneurl, strlen(cloneurl));
    370 		fputs("\">", fp);
    371 		xmlencode(fp, cloneurl, strlen(cloneurl));
    372 		fputs("</a></code>", fp);
    373 	}
    374 	fputs("</header><nav>\n", fp);
    375 	fprintf(fp, " <a rel=\"version-history\" href=\"%slog.html\">Log</a>", relpath);
    376 	fprintf(fp, " (<a rel=\"alternate\" type=\"application/atom+xml\" title=\"%s Atom Feed\" href=\"%satom.xml\">atom</a>)",
    377 		name, relpath);
    378 	fprintf(fp, " <a rel=\"index\" href=\"%sfiles.html\">Files</a>", relpath);
    379 	fprintf(fp, " <a href=\"%srefs.html\">Refs</a>", relpath);
    380 	if (submodules)
    381 		fprintf(fp, " <a href=\"%sfile/%s.html\">Submodules</a>",
    382 		        relpath, submodules);
    383 	if (readme)
    384 		fprintf(fp, " <a href=\"%sfile/%s.html\">README</a>",
    385 		        relpath, readme);
    386 	if (license)
    387 		fprintf(fp, " <a href=\"%sfile/%s.html\">LICENSE</a>",
    388 		        relpath, license);
    389 	fputs("</nav>\n<main>\n", fp);
    390 }
    391 
    392 void
    393 writefooter(FILE *fp)
    394 {
    395 	fputs("</main>\n", fp);
    396 	fputs("\t<footer>Please <a href=\"https://hacktivis.me/about\">contact me</a> by any means for patches, issues(tracker will maybe be added oneday), thanks/donations, or whatever else.</footer>\n", fp);
    397 	fputs("</body>\n</html>\n", fp);
    398 }
    399 
    400 int
    401 writeblobhtml(FILE *fp, const git_blob *blob)
    402 {
    403 	size_t n = 0, i, prev;
    404 	const char *nfmt = "<a href=\"#l%d\" class=\"line\" id=\"l%d\">%7d</a> ";
    405 	const char *s = git_blob_rawcontent(blob);
    406 	git_off_t len = git_blob_rawsize(blob);
    407 
    408 	fputs("<pre id=\"blob\">\n", fp);
    409 
    410 	if (len > 0) {
    411 		for (i = 0, prev = 0; i < (size_t)len; i++) {
    412 			if (s[i] != '\n')
    413 				continue;
    414 			n++;
    415 			fprintf(fp, nfmt, n, n, n);
    416 			xmlencode(fp, &s[prev], i - prev + 1);
    417 			prev = i + 1;
    418 		}
    419 		/* trailing data */
    420 		if ((len - prev) > 0) {
    421 			n++;
    422 			fprintf(fp, nfmt, n, n, n);
    423 			xmlencode(fp, &s[prev], len - prev);
    424 		}
    425 	}
    426 
    427 	fputs("</pre>\n", fp);
    428 
    429 	return n;
    430 }
    431 
    432 void
    433 printcommit(FILE *fp, struct commitinfo *ci)
    434 {
    435 	fprintf(fp, "<strong>commit:</strong> <a href=\"%scommit/%s.html\">%s</a>\n",
    436 		relpath, ci->oid, ci->oid);
    437 
    438 	if (ci->parentoid[0])
    439 		fprintf(fp, "<strong>parent:</strong> <a href=\"%scommit/%s.html\">%s</a>\n",
    440 			relpath, ci->parentoid, ci->parentoid);
    441 
    442 	if (ci->author) {
    443 		fputs("<strong>Author:</strong> ", fp);
    444 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    445 		fputs(" &lt;<a href=\"mailto:", fp);
    446 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    447 		fputs("\">", fp);
    448 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    449 		fputs("</a>&gt;\n<strong>Date:</strong>   ", fp);
    450 		printtime(fp, &(ci->author->when));
    451 		fputc('\n', fp);
    452 	}
    453 	if (ci->msg) {
    454 		fputc('\n', fp);
    455 		xmlencode(fp, ci->msg, strlen(ci->msg));
    456 		fputc('\n', fp);
    457 	}
    458 }
    459 
    460 void
    461 printshowfile(FILE *fp, struct commitinfo *ci)
    462 {
    463 	const git_diff_delta *delta;
    464 	const git_diff_hunk *hunk;
    465 	const git_diff_line *line;
    466 	git_patch *patch;
    467 	size_t nhunks, nhunklines, changed, add, del, total, i, j, k;
    468 	char linestr[80];
    469 	int c;
    470 
    471 	printcommit(fp, ci);
    472 
    473 	if (!ci->deltas)
    474 		return;
    475 
    476 	if (ci->filecount > 1000   ||
    477 	    ci->ndeltas   > 1000   ||
    478 	    ci->addcount  > 100000 ||
    479 	    ci->delcount  > 100000) {
    480 		fputs("Diff is too large, output suppressed.\n", fp);
    481 		return;
    482 	}
    483 
    484 	/* diff stat */
    485 	fputs("<h2>Diffstat:</h2>\n<table>", fp);
    486 	for (i = 0; i < ci->ndeltas; i++) {
    487 		delta = git_patch_get_delta(ci->deltas[i]->patch);
    488 
    489 		switch (delta->status) {
    490 		case GIT_DELTA_ADDED:      c = 'A'; break;
    491 		case GIT_DELTA_COPIED:     c = 'C'; break;
    492 		case GIT_DELTA_DELETED:    c = 'D'; break;
    493 		case GIT_DELTA_MODIFIED:   c = 'M'; break;
    494 		case GIT_DELTA_RENAMED:    c = 'R'; break;
    495 		case GIT_DELTA_TYPECHANGE: c = 'T'; break;
    496 		default:                   c = ' '; break;
    497 		}
    498 		if (c == ' ')
    499 			fprintf(fp, "<tr><td>%c", c);
    500 		else
    501 			fprintf(fp, "<tr><td class=\"%c\">%c", c, c);
    502 
    503 		fprintf(fp, "</td><td><a href=\"#h%zu\">", i);
    504 		xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
    505 		if (strcmp(delta->old_file.path, delta->new_file.path)) {
    506 			fputs(" -&gt; ", fp);
    507 			xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
    508 		}
    509 
    510 		add = ci->deltas[i]->addcount;
    511 		del = ci->deltas[i]->delcount;
    512 		changed = add + del;
    513 		total = sizeof(linestr) - 2;
    514 		if (changed > total) {
    515 			if (add)
    516 				add = ((float)total / changed * add) + 1;
    517 			if (del)
    518 				del = ((float)total / changed * del) + 1;
    519 		}
    520 		memset(&linestr, '+', add);
    521 		memset(&linestr[add], '-', del);
    522 
    523 		fprintf(fp, "</a></td><td class=\"num\">%zu</td><td><span class=\"i\">",
    524 		        ci->deltas[i]->addcount + ci->deltas[i]->delcount);
    525 		fwrite(&linestr, 1, add, fp);
    526 		fputs("</span><span class=\"d\">", fp);
    527 		fwrite(&linestr[add], 1, del, fp);
    528 		fputs("</span></td></tr>\n", fp);
    529 	}
    530 	fprintf(fp, "</table></pre><pre>%zu file%s changed, %zu insertion%s(+), %zu deletion%s(-)\n",
    531 		ci->filecount, ci->filecount == 1 ? "" : "s",
    532 	        ci->addcount,  ci->addcount  == 1 ? "" : "s",
    533 	        ci->delcount,  ci->delcount  == 1 ? "" : "s");
    534 
    535 	fputs("<hr/>", fp);
    536 
    537 	for (i = 0; i < ci->ndeltas; i++) {
    538 		patch = ci->deltas[i]->patch;
    539 		delta = git_patch_get_delta(patch);
    540 		fprintf(fp, "<strong>diff --git a/<a id=\"h%zu\" href=\"%sfile/", i, relpath);
    541 		xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
    542 		fputs(".html\">", fp);
    543 		xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
    544 		fprintf(fp, "</a> b/<a href=\"%sfile/", relpath);
    545 		xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
    546 		fprintf(fp, ".html\">");
    547 		xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
    548 		fprintf(fp, "</a></strong>\n");
    549 
    550 		/* check binary data */
    551 		if (delta->flags & GIT_DIFF_FLAG_BINARY) {
    552 			fputs("Binary files differ.\n", fp);
    553 			continue;
    554 		}
    555 
    556 		nhunks = git_patch_num_hunks(patch);
    557 		for (j = 0; j < nhunks; j++) {
    558 			if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
    559 				break;
    560 
    561 			fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"h\">", i, j, i, j);
    562 			xmlencode(fp, hunk->header, hunk->header_len);
    563 			fputs("</a>", fp);
    564 
    565 			for (k = 0; ; k++) {
    566 				if (git_patch_get_line_in_hunk(&line, patch, j, k))
    567 					break;
    568 				if (line->old_lineno == -1)
    569 					fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"i\">+",
    570 						i, j, k, i, j, k);
    571 				else if (line->new_lineno == -1)
    572 					fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"d\">-",
    573 						i, j, k, i, j, k);
    574 				else
    575 					fputc(' ', fp);
    576 				xmlencode(fp, line->content, line->content_len);
    577 				if (line->old_lineno == -1 || line->new_lineno == -1)
    578 					fputs("</a>", fp);
    579 			}
    580 		}
    581 	}
    582 }
    583 
    584 void
    585 writelogline(FILE *fp, struct commitinfo *ci)
    586 {
    587 	fputs("<tr><td class=\"date log-author-date\">", fp);
    588 	if (ci->author)
    589 		printtimeshort(fp, &(ci->author->when));
    590 	fputs("</td><td class=\"text log-summary\">", fp);
    591 	if (ci->summary) {
    592 		fprintf(fp, "<a href=\"%scommit/%s.html\">", relpath, ci->oid);
    593 		xmlencode(fp, ci->summary, strlen(ci->summary));
    594 		fputs("</a>", fp);
    595 	}
    596 	fputs("</td><td class=\"text log-author\">", fp);
    597 	if (ci->author)
    598 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    599 	fputs("</td><td class=\"num log-filecount\">", fp);
    600 	fprintf(fp, "%zu", ci->filecount);
    601 	fputs("</td><td class=\"num log-addcount\">", fp);
    602 	fprintf(fp, "+%zu", ci->addcount);
    603 	fputs("</td><td class=\"num log-delcount\">", fp);
    604 	fprintf(fp, "-%zu", ci->delcount);
    605 	fputs("</td></tr>\n", fp);
    606 }
    607 
    608 int
    609 writelog(FILE *fp, const git_oid *oid)
    610 {
    611 	struct commitinfo *ci;
    612 	git_revwalk *w = NULL;
    613 	git_oid id;
    614 	char path[PATH_MAX], oidstr[GIT_OID_HEXSZ + 1];
    615 	FILE *fpfile;
    616 	int r;
    617 
    618 	git_revwalk_new(&w, repo);
    619 	git_revwalk_push(w, oid);
    620 	git_revwalk_simplify_first_parent(w);
    621 
    622 	while (!git_revwalk_next(&id, w)) {
    623 		relpath = "";
    624 
    625 		if (cachefile && !memcmp(&id, &lastoid, sizeof(id)))
    626 			break;
    627 
    628 		git_oid_tostr(oidstr, sizeof(oidstr), &id);
    629 		r = snprintf(path, sizeof(path), "commit/%s.html", oidstr);
    630 		if (r < 0 || (size_t)r >= sizeof(path))
    631 			errx(1, "path truncated: 'commit/%s.html'", oidstr);
    632 		r = access(path, F_OK);
    633 
    634 		/* optimization: if there are no log lines to write and
    635 		   the commit file already exists: skip the diffstat */
    636 		if (!nlogcommits && !r)
    637 			continue;
    638 
    639 		if (!(ci = commitinfo_getbyoid(&id)))
    640 			break;
    641 		/* diffstat: for stagit HTML required for the log.html line */
    642 		if (commitinfo_getstats(ci) == -1)
    643 			goto err;
    644 
    645 		if (nlogcommits < 0) {
    646 			writelogline(fp, ci);
    647 		} else if (nlogcommits > 0) {
    648 			writelogline(fp, ci);
    649 			nlogcommits--;
    650 			if (!nlogcommits && ci->parentoid[0])
    651 				fputs("<tr><td></td><td colspan=\"5\">"
    652 				      "More commits remaining [...]</td>"
    653 				      "</tr>\n", fp);
    654 		}
    655 
    656 		if (cachefile)
    657 			writelogline(wcachefp, ci);
    658 
    659 		/* check if file exists if so skip it */
    660 		if (r) {
    661 			relpath = "../";
    662 			fpfile = efopen(path, "w");
    663 			writeheader(fpfile, ci->summary);
    664 			fputs("<pre>", fpfile);
    665 			printshowfile(fpfile, ci);
    666 			fputs("</pre>\n", fpfile);
    667 			writefooter(fpfile);
    668 			fclose(fpfile);
    669 		}
    670 err:
    671 		commitinfo_free(ci);
    672 	}
    673 	git_revwalk_free(w);
    674 
    675 	relpath = "";
    676 
    677 	return 0;
    678 }
    679 
    680 void
    681 printcommitatom(FILE *fp, struct commitinfo *ci)
    682 {
    683 	fputs("<entry>\n", fp);
    684 
    685 	fprintf(fp, "<id>%s</id>\n", ci->oid);
    686 	if (ci->author) {
    687 		fputs("<published>", fp);
    688 		printtimez(fp, &(ci->author->when));
    689 		fputs("</published>\n", fp);
    690 	}
    691 	if (ci->committer) {
    692 		fputs("<updated>", fp);
    693 		printtimez(fp, &(ci->committer->when));
    694 		fputs("</updated>\n", fp);
    695 	}
    696 	if (ci->summary) {
    697 		fputs("<title type=\"text\">", fp);
    698 		xmlencode(fp, ci->summary, strlen(ci->summary));
    699 		fputs("</title>\n", fp);
    700 	}
    701 	fprintf(fp, "<link rel=\"alternate\" type=\"text/html\" href=\"commit/%s.html\" />",
    702 	        ci->oid);
    703 
    704 	if (ci->author) {
    705 		fputs("<author><name>", fp);
    706 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    707 		fputs("</name>\n<email>", fp);
    708 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    709 		fputs("</email>\n</author>\n", fp);
    710 	}
    711 
    712 	fputs("<content type=\"text\">", fp);
    713 	fprintf(fp, "commit %s\n", ci->oid);
    714 	if (ci->parentoid[0])
    715 		fprintf(fp, "parent %s\n", ci->parentoid);
    716 	if (ci->author) {
    717 		fputs("Author: ", fp);
    718 		xmlencode(fp, ci->author->name, strlen(ci->author->name));
    719 		fputs(" &lt;", fp);
    720 		xmlencode(fp, ci->author->email, strlen(ci->author->email));
    721 		fputs("&gt;\nDate:   ", fp);
    722 		printtime(fp, &(ci->author->when));
    723 		fputc('\n', fp);
    724 	}
    725 	if (ci->msg) {
    726 		fputc('\n', fp);
    727 		xmlencode(fp, ci->msg, strlen(ci->msg));
    728 	}
    729 	fputs("\n</content>\n</entry>\n", fp);
    730 }
    731 
    732 int
    733 writeatom(FILE *fp)
    734 {
    735 	struct commitinfo *ci;
    736 	git_revwalk *w = NULL;
    737 	git_oid id;
    738 	size_t i, m = 100; /* last 'm' commits */
    739 
    740 	fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    741 	      "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n<title>", fp);
    742 	xmlencode(fp, strippedname, strlen(strippedname));
    743 	fputs(", branch HEAD</title>\n<subtitle>", fp);
    744 	xmlencode(fp, description, strlen(description));
    745 	fputs("</subtitle>\n", fp);
    746 
    747 	git_revwalk_new(&w, repo);
    748 	git_revwalk_push_head(w);
    749 	git_revwalk_simplify_first_parent(w);
    750 
    751 	for (i = 0; i < m && !git_revwalk_next(&id, w); i++) {
    752 		if (!(ci = commitinfo_getbyoid(&id)))
    753 			break;
    754 		printcommitatom(fp, ci);
    755 		commitinfo_free(ci);
    756 	}
    757 	git_revwalk_free(w);
    758 
    759 	fputs("</feed>\n", fp);
    760 
    761 	return 0;
    762 }
    763 
    764 int
    765 writeblob(git_object *obj, const char *fpath, const char *filename, git_off_t filesize)
    766 {
    767 	char tmp[PATH_MAX] = "", *d;
    768 	const char *p;
    769 	int lc = 0;
    770 	FILE *fp;
    771 
    772 	if (strlcpy(tmp, fpath, sizeof(tmp)) >= sizeof(tmp))
    773 		errx(1, "path truncated: '%s'", fpath);
    774 	if (!(d = dirname(tmp)))
    775 		err(1, "dirname");
    776 	if (mkdirp(d))
    777 		return -1;
    778 
    779 	for (p = fpath, tmp[0] = '\0'; *p; p++) {
    780 		if (*p == '/' && strlcat(tmp, "../", sizeof(tmp)) >= sizeof(tmp))
    781 			errx(1, "path truncated: '../%s'", tmp);
    782 	}
    783 	relpath = tmp;
    784 
    785 	fp = efopen(fpath, "w");
    786 	writeheader(fp, filename);
    787 	fputs("<p> ", fp);
    788 	xmlencode(fp, filename, strlen(filename));
    789 	fprintf(fp, " (%juB)", (uintmax_t)filesize);
    790 	fputs("</p><hr/>", fp);
    791 
    792 	if (git_blob_is_binary((git_blob *)obj)) {
    793 		fputs("<p>Binary file.</p>\n", fp);
    794 	} else {
    795 		lc = writeblobhtml(fp, (git_blob *)obj);
    796 		if (ferror(fp))
    797 			err(1, "fwrite");
    798 	}
    799 	writefooter(fp);
    800 	fclose(fp);
    801 
    802 	relpath = "";
    803 
    804 	return lc;
    805 }
    806 
    807 const char *
    808 filemode(git_filemode_t m)
    809 {
    810 	static char mode[11];
    811 
    812 	memset(mode, '-', sizeof(mode) - 1);
    813 	mode[10] = '\0';
    814 
    815 	if (S_ISREG(m))
    816 		mode[0] = '-';
    817 	else if (S_ISBLK(m))
    818 		mode[0] = 'b';
    819 	else if (S_ISCHR(m))
    820 		mode[0] = 'c';
    821 	else if (S_ISDIR(m))
    822 		mode[0] = 'd';
    823 	else if (S_ISFIFO(m))
    824 		mode[0] = 'p';
    825 	else if (S_ISLNK(m))
    826 		mode[0] = 'l';
    827 	else if (S_ISSOCK(m))
    828 		mode[0] = 's';
    829 	else
    830 		mode[0] = '?';
    831 
    832 	if (m & S_IRUSR) mode[1] = 'r';
    833 	if (m & S_IWUSR) mode[2] = 'w';
    834 	if (m & S_IXUSR) mode[3] = 'x';
    835 	if (m & S_IRGRP) mode[4] = 'r';
    836 	if (m & S_IWGRP) mode[5] = 'w';
    837 	if (m & S_IXGRP) mode[6] = 'x';
    838 	if (m & S_IROTH) mode[7] = 'r';
    839 	if (m & S_IWOTH) mode[8] = 'w';
    840 	if (m & S_IXOTH) mode[9] = 'x';
    841 
    842 	if (m & S_ISUID) mode[3] = (mode[3] == 'x') ? 's' : 'S';
    843 	if (m & S_ISGID) mode[6] = (mode[6] == 'x') ? 's' : 'S';
    844 	if (m & S_ISVTX) mode[9] = (mode[9] == 'x') ? 't' : 'T';
    845 
    846 	return mode;
    847 }
    848 
    849 int
    850 writefilestree(FILE *fp, git_tree *tree, const char *path)
    851 {
    852 	const git_tree_entry *entry = NULL;
    853 	git_submodule *module = NULL;
    854 	git_object *obj = NULL;
    855 	git_off_t filesize;
    856 	const char *entryname;
    857 	char filepath[PATH_MAX], entrypath[PATH_MAX];
    858 	size_t count, i;
    859 	int lc, r, ret;
    860 
    861 	count = git_tree_entrycount(tree);
    862 	for (i = 0; i < count; i++) {
    863 		if (!(entry = git_tree_entry_byindex(tree, i)) ||
    864 		    !(entryname = git_tree_entry_name(entry)))
    865 			return -1;
    866 		joinpath(entrypath, sizeof(entrypath), path, entryname);
    867 
    868 		r = snprintf(filepath, sizeof(filepath), "file/%s.html",
    869 		         entrypath);
    870 		if (r < 0 || (size_t)r >= sizeof(filepath))
    871 			errx(1, "path truncated: 'file/%s.html'", entrypath);
    872 
    873 		if (!git_tree_entry_to_object(&obj, repo, entry)) {
    874 			switch (git_object_type(obj)) {
    875 			case GIT_OBJ_BLOB:
    876 				break;
    877 			case GIT_OBJ_TREE:
    878 				/* NOTE: recurses */
    879 				ret = writefilestree(fp, (git_tree *)obj,
    880 				                     entrypath);
    881 				git_object_free(obj);
    882 				if (ret)
    883 					return ret;
    884 				continue;
    885 			default:
    886 				git_object_free(obj);
    887 				continue;
    888 			}
    889 
    890 			filesize = git_blob_rawsize((git_blob *)obj);
    891 			lc = writeblob(obj, filepath, entryname, filesize);
    892 
    893 			fputs("<tr><td>", fp);
    894 			fputs(filemode(git_tree_entry_filemode(entry)), fp);
    895 			fprintf(fp, "</td><td><a href=\"%s", relpath);
    896 			xmlencode(fp, filepath, strlen(filepath));
    897 			fputs("\">", fp);
    898 			xmlencode(fp, entrypath, strlen(entrypath));
    899 			fputs("</a></td><td class=\"num\" align=\"right\">", fp);
    900 			if (lc > 0)
    901 				fprintf(fp, "%dL", lc);
    902 			else
    903 				fprintf(fp, "%juB", (uintmax_t)filesize);
    904 			fputs("</td></tr>\n", fp);
    905 			git_object_free(obj);
    906 		} else if (!git_submodule_lookup(&module, repo, entryname)) {
    907 			fprintf(fp, "<tr><td>m---------</td><td><a href=\"%sfile/.gitmodules.html\">",
    908 				relpath);
    909 			xmlencode(fp, entrypath, strlen(entrypath));
    910 			git_submodule_free(module);
    911 			fputs("</a></td><td class=\"num\" align=\"right\"></td></tr>\n", fp);
    912 		}
    913 	}
    914 
    915 	return 0;
    916 }
    917 
    918 int
    919 writefiles(FILE *fp, const git_oid *id)
    920 {
    921 	git_tree *tree = NULL;
    922 	git_commit *commit = NULL;
    923 	int ret = -1;
    924 
    925 	fputs("<table id=\"files\"><thead>\n<tr>"
    926 	      "<td>Mode</td><td>Name</td><td class=\"num\">Size</td>"
    927 	      "</tr>\n</thead><tbody>\n", fp);
    928 
    929 	if (!git_commit_lookup(&commit, repo, id) &&
    930 	    !git_commit_tree(&tree, commit))
    931 		ret = writefilestree(fp, tree, "");
    932 
    933 	fputs("</tbody></table>", fp);
    934 
    935 	git_commit_free(commit);
    936 	git_tree_free(tree);
    937 
    938 	return ret;
    939 }
    940 
    941 int
    942 refs_cmp(const void *v1, const void *v2)
    943 {
    944 	git_reference *r1 = (*(git_reference **)v1);
    945 	git_reference *r2 = (*(git_reference **)v2);
    946 	int r;
    947 
    948 	if ((r = git_reference_is_branch(r1) - git_reference_is_branch(r2)))
    949 		return r;
    950 
    951 	return strcmp(git_reference_shorthand(r1),
    952 	              git_reference_shorthand(r2));
    953 }
    954 
    955 int
    956 writerefs(FILE *fp)
    957 {
    958 	struct commitinfo *ci;
    959 	const git_oid *id = NULL;
    960 	git_object *obj = NULL;
    961 	git_reference *dref = NULL, *r, *ref = NULL;
    962 	git_reference_iterator *it = NULL;
    963 	git_reference **refs = NULL;
    964 	size_t count, i, j, refcount;
    965 	const char *titles[] = { "Branches", "Tags" };
    966 	const char *ids[] = { "branches", "tags" };
    967 	const char *name;
    968 
    969 	if (git_reference_iterator_new(&it, repo))
    970 		return -1;
    971 
    972 	for (refcount = 0; !git_reference_next(&ref, it); refcount++) {
    973 		if (!(refs = reallocarray(refs, refcount + 1, sizeof(git_reference *))))
    974 			err(1, "realloc");
    975 		refs[refcount] = ref;
    976 	}
    977 	git_reference_iterator_free(it);
    978 
    979 	/* sort by type then shorthand name */
    980 	qsort(refs, refcount, sizeof(git_reference *), refs_cmp);
    981 
    982 	for (j = 0; j < 2; j++) {
    983 		for (i = 0, count = 0; i < refcount; i++) {
    984 			if (!(git_reference_is_branch(refs[i]) && j == 0) &&
    985 			    !(git_reference_is_tag(refs[i]) && j == 1))
    986 				continue;
    987 
    988 			switch (git_reference_type(refs[i])) {
    989 			case GIT_REF_SYMBOLIC:
    990 				if (git_reference_resolve(&dref, refs[i]))
    991 					goto err;
    992 				r = dref;
    993 				break;
    994 			case GIT_REF_OID:
    995 				r = refs[i];
    996 				break;
    997 			default:
    998 				continue;
    999 			}
   1000 			if (!git_reference_target(r) ||
   1001 			    git_reference_peel(&obj, r, GIT_OBJ_ANY))
   1002 				goto err;
   1003 			if (!(id = git_object_id(obj)))
   1004 				goto err;
   1005 			if (!(ci = commitinfo_getbyoid(id)))
   1006 				break;
   1007 
   1008 			/* print header if it has an entry (first). */
   1009 			if (++count == 1) {
   1010 				fprintf(fp, "<h2>%s</h2><table id=\"%s\">"
   1011 			                "<thead>\n<tr><td>Name</td>"
   1012 				        "<td>Last commit date</td>"
   1013 				        "<td>Author</td>\n</tr>\n"
   1014 				        "</thead><tbody>\n",
   1015 				         titles[j], ids[j]);
   1016 			}
   1017 
   1018 			relpath = "";
   1019 			name = git_reference_shorthand(r);
   1020 
   1021 			fputs("<tr><td>", fp);
   1022 			xmlencode(fp, name, strlen(name));
   1023 			fputs("</td><td>", fp);
   1024 			if (ci->author)
   1025 				printtimeshort(fp, &(ci->author->when));
   1026 			fputs("</td><td>", fp);
   1027 			if (ci->author)
   1028 				xmlencode(fp, ci->author->name, strlen(ci->author->name));
   1029 			fputs("</td></tr>\n", fp);
   1030 
   1031 			relpath = "../";
   1032 
   1033 			commitinfo_free(ci);
   1034 			git_object_free(obj);
   1035 			obj = NULL;
   1036 			git_reference_free(dref);
   1037 			dref = NULL;
   1038 		}
   1039 		/* table footer */
   1040 		if (count)
   1041 			fputs("</tbody></table><br/>", fp);
   1042 	}
   1043 
   1044 err:
   1045 	git_object_free(obj);
   1046 	git_reference_free(dref);
   1047 
   1048 	for (i = 0; i < refcount; i++)
   1049 		git_reference_free(refs[i]);
   1050 	free(refs);
   1051 
   1052 	return 0;
   1053 }
   1054 
   1055 void
   1056 usage(char *argv0)
   1057 {
   1058 	fprintf(stderr, "%s [-c cachefile | -l commits] repodir\n", argv0);
   1059 	exit(1);
   1060 }
   1061 
   1062 int
   1063 main(int argc, char *argv[])
   1064 {
   1065 	git_object *obj = NULL;
   1066 	const git_oid *head = NULL;
   1067 	mode_t mask;
   1068 	FILE *fp, *fpread;
   1069 	char path[PATH_MAX], repodirabs[PATH_MAX + 1], *p;
   1070 	char tmppath[64] = "cache.XXXXXXXXXXXX", buf[BUFSIZ];
   1071 	size_t n;
   1072 	int i, fd;
   1073 
   1074 	for (i = 1; i < argc; i++) {
   1075 		if (argv[i][0] != '-') {
   1076 			if (repodir)
   1077 				usage(argv[0]);
   1078 			repodir = argv[i];
   1079 		} else if (argv[i][1] == 'c') {
   1080 			if (nlogcommits > 0 || i + 1 >= argc)
   1081 				usage(argv[0]);
   1082 			cachefile = argv[++i];
   1083 		} else if (argv[i][1] == 'l') {
   1084 			if (cachefile || i + 1 >= argc)
   1085 				usage(argv[0]);
   1086 			errno = 0;
   1087 			nlogcommits = strtoll(argv[++i], &p, 10);
   1088 			if (argv[i][0] == '\0' || *p != '\0' ||
   1089 			    nlogcommits <= 0 || errno)
   1090 				usage(argv[0]);
   1091 		}
   1092 	}
   1093 	if (!repodir)
   1094 		usage(argv[0]);
   1095 
   1096 	if (!realpath(repodir, repodirabs))
   1097 		err(1, "realpath");
   1098 
   1099 	git_libgit2_init();
   1100 
   1101 #ifdef __OpenBSD__
   1102 	if (cachefile) {
   1103 		if (pledge("stdio rpath wpath cpath fattr", NULL) == -1)
   1104 			err(1, "pledge");
   1105 	} else {
   1106 		if (pledge("stdio rpath wpath cpath", NULL) == -1)
   1107 			err(1, "pledge");
   1108 	}
   1109 #endif
   1110 
   1111 	if (git_repository_open_ext(&repo, repodir,
   1112 		GIT_REPOSITORY_OPEN_NO_SEARCH, NULL) < 0) {
   1113 		fprintf(stderr, "%s: cannot open repository\n", argv[0]);
   1114 		return 1;
   1115 	}
   1116 
   1117 	/* find HEAD */
   1118 	if (!git_revparse_single(&obj, repo, "HEAD"))
   1119 		head = git_object_id(obj);
   1120 	git_object_free(obj);
   1121 
   1122 	/* use directory name as name */
   1123 	if ((name = strrchr(repodirabs, '/')))
   1124 		name++;
   1125 	else
   1126 		name = "";
   1127 
   1128 	/* strip .git suffix */
   1129 	if (!(strippedname = strdup(name)))
   1130 		err(1, "strdup");
   1131 	if ((p = strrchr(strippedname, '.')))
   1132 		if (!strcmp(p, ".git"))
   1133 			*p = '\0';
   1134 
   1135 	/* read description or .git/description */
   1136 	joinpath(path, sizeof(path), repodir, "description");
   1137 	if (!(fpread = fopen(path, "r"))) {
   1138 		joinpath(path, sizeof(path), repodir, ".git/description");
   1139 		fpread = fopen(path, "r");
   1140 	}
   1141 	if (fpread) {
   1142 		if (!fgets(description, sizeof(description), fpread))
   1143 			description[0] = '\0';
   1144 		fclose(fpread);
   1145 	}
   1146 
   1147 	/* read url or .git/url */
   1148 	joinpath(path, sizeof(path), repodir, "url");
   1149 	if (!(fpread = fopen(path, "r"))) {
   1150 		joinpath(path, sizeof(path), repodir, ".git/url");
   1151 		fpread = fopen(path, "r");
   1152 	}
   1153 	if (fpread) {
   1154 		if (!fgets(cloneurl, sizeof(cloneurl), fpread))
   1155 			cloneurl[0] = '\0';
   1156 		cloneurl[strcspn(cloneurl, "\n")] = '\0';
   1157 		fclose(fpread);
   1158 	}
   1159 
   1160 	/* check LICENSE */
   1161 	for (i = 0; i < sizeof(licensefiles) / sizeof(*licensefiles) && !license; i++) {
   1162 		if (!git_revparse_single(&obj, repo, licensefiles[i]) &&
   1163 		    git_object_type(obj) == GIT_OBJ_BLOB)
   1164 			license = licensefiles[i] + strlen("HEAD:");
   1165 		git_object_free(obj);
   1166 	}
   1167 
   1168 	/* check README */
   1169 	for (i = 0; i < sizeof(readmefiles) / sizeof(*readmefiles) && !readme; i++) {
   1170 		if (!git_revparse_single(&obj, repo, readmefiles[i]) &&
   1171 		    git_object_type(obj) == GIT_OBJ_BLOB)
   1172 			readme = readmefiles[i] + strlen("HEAD:");
   1173 		git_object_free(obj);
   1174 	}
   1175 
   1176 	if (!git_revparse_single(&obj, repo, "HEAD:.gitmodules") &&
   1177 	    git_object_type(obj) == GIT_OBJ_BLOB)
   1178 		submodules = ".gitmodules";
   1179 	git_object_free(obj);
   1180 
   1181 	/* log for HEAD */
   1182 	fp = efopen("log.html", "w");
   1183 	relpath = "";
   1184 	mkdir("commit", S_IRWXU | S_IRWXG | S_IRWXO);
   1185 	writeheader(fp, "Log");
   1186 	fputs("<table id=\"log\"><thead>\n<tr><td>Date</td>"
   1187 	      "<td>Commit message</td>"
   1188 	      "<td>Author</td><td class=\"num\" align=\"right\">Files</td>"
   1189 	      "<td class=\"num\" align=\"right\">+</td>"
   1190 	      "<td class=\"num\" align=\"right\">-</td></tr>\n</thead><tbody>\n", fp);
   1191 
   1192 	if (cachefile && head) {
   1193 		/* read from cache file (does not need to exist) */
   1194 		if ((rcachefp = fopen(cachefile, "r"))) {
   1195 			if (!fgets(lastoidstr, sizeof(lastoidstr), rcachefp))
   1196 				errx(1, "%s: no object id", cachefile);
   1197 			if (git_oid_fromstr(&lastoid, lastoidstr))
   1198 				errx(1, "%s: invalid object id", cachefile);
   1199 		}
   1200 
   1201 		/* write log to (temporary) cache */
   1202 		if ((fd = mkstemp(tmppath)) == -1)
   1203 			err(1, "mkstemp");
   1204 		if (!(wcachefp = fdopen(fd, "w")))
   1205 			err(1, "fdopen: '%s'", tmppath);
   1206 		/* write last commit id (HEAD) */
   1207 		git_oid_tostr(buf, sizeof(buf), head);
   1208 		fprintf(wcachefp, "%s\n", buf);
   1209 
   1210 		writelog(fp, head);
   1211 
   1212 		if (rcachefp) {
   1213 			/* append previous log to log.html and the new cache */
   1214 			while (!feof(rcachefp)) {
   1215 				n = fread(buf, 1, sizeof(buf), rcachefp);
   1216 				if (ferror(rcachefp))
   1217 					err(1, "fread");
   1218 				if (fwrite(buf, 1, n, fp) != n ||
   1219 				    fwrite(buf, 1, n, wcachefp) != n)
   1220 					err(1, "fwrite");
   1221 			}
   1222 			fclose(rcachefp);
   1223 		}
   1224 		fclose(wcachefp);
   1225 	} else {
   1226 		if (head)
   1227 			writelog(fp, head);
   1228 	}
   1229 
   1230 	fputs("</tbody></table>", fp);
   1231 	writefooter(fp);
   1232 	fclose(fp);
   1233 
   1234 	/* files for HEAD */
   1235 	fp = efopen("files.html", "w");
   1236 	writeheader(fp, "Files");
   1237 	if (head)
   1238 		writefiles(fp, head);
   1239 	writefooter(fp);
   1240 	fclose(fp);
   1241 
   1242 	/* summary page with branches and tags */
   1243 	fp = efopen("refs.html", "w");
   1244 	writeheader(fp, "Refs");
   1245 	writerefs(fp);
   1246 	writefooter(fp);
   1247 	fclose(fp);
   1248 
   1249 	/* Atom feed */
   1250 	fp = efopen("atom.xml", "w");
   1251 	writeatom(fp);
   1252 	fclose(fp);
   1253 
   1254 	/* rename new cache file on success */
   1255 	if (cachefile && head) {
   1256 		if (rename(tmppath, cachefile))
   1257 			err(1, "rename: '%s' to '%s'", tmppath, cachefile);
   1258 		umask((mask = umask(0)));
   1259 		if (chmod(cachefile,
   1260 		    (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) & ~mask))
   1261 			err(1, "chmod: '%s'", cachefile);
   1262 	}
   1263 
   1264 	/* cleanup */
   1265 	git_repository_free(repo);
   1266 	git_libgit2_shutdown();
   1267 
   1268 	return 0;
   1269 }