stagit

static git page generator
git clone http://git.hanabi.in/repos/stagit.git
Log | Files | Refs | README | LICENSE

stagit.c (35306B)


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