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