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