stagit.c (38624B) - raw


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