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