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