stagit

- static git page generator
git clone git://git.acid.vegas/stagit.git
Log | Files | Refs | Archive | README | LICENSE

stagit.c (37443B)

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