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