stagit

static git page generator - with my changes
git clone https://pi.duncano.de/git/stagit.git

stagit.c (29910B)


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