stagit

Personal stagit fork
git clone git://git.alexwennerberg.com/stagit
Log | Files | Refs | README | LICENSE

stagit.c (35269B) - raw


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