stagit

static git page generator (local tweaks)
git clone https://wehaveforgeathome.hates.computer/stagit.git
Log | Files | Refs | LICENSE

stagit.c (36474B)


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