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