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