stagit

Fork of stagit (git://git.codemadness.org/stagit) with personal tweaks.
git clone https://git.philomathiclife.com/repos/stagit
Log | Files | Refs | README | LICENSE

stagit.c (36242B)


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