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