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