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