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