stagit

static git page generator (mirror)
git clone git://git.2f30.org/stagit
Log | Files | Refs | README | LICENSE

stagit.c (33800B)


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