stagit

stagit (https://www.codemadness.org/stagit.html) fork
git clone git://bsandro.tech/stagit
Log | Files | Refs | README | LICENSE

stagit.c (34580B)


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