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