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