stagit

Personal stagit fork
git clone git://git.alexwennerberg.com/stagit
Log | Files | Refs | README | LICENSE

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