stagit

My personal fork of stagit https://codemadness.org/stagit.html
git clone https://git.grace.moe/stagit
Log | Files | Refs | README | LICENSE

stagit.c (39977B)


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