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