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