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