stagit

Fork of stagit - for personal repository
git clone git://git.dimitrijedobrota.com/stagit.git
Log | Files | Refs | README | LICENSE

stagit.c (34882B)


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