codeview

A light and fast web based git repository viewer

Log | Files | Refs | README | LICENSE

stagit.c (39334B)


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