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