stagit

static git page - forked from git.codemadness.org/stagit
git clone git://src.gearsix.net/stagitstagit.zip
Log | Files | Refs | Atom | README | LICENSE

stagit.c (raw) (38394B)


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