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