stagit

static git page - forked from git.codemadness.org/stagit
git clone git://src.gearsix.net/stagit
Log | Files | Refs | Atom | README | LICENSE

stagit.c (37055B)


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