]> git.armaanb.net Git - stagit.git/blob - stagit.c
Use the recommended HTML5 document type.
[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 commitinfo {
19         const git_oid *id;
20
21         char oid[GIT_OID_HEXSZ + 1];
22         char parentoid[GIT_OID_HEXSZ + 1];
23
24         const git_signature *author;
25         const char          *summary;
26         const char          *msg;
27
28         git_diff_stats *stats;
29         git_diff       *diff;
30         git_commit     *commit;
31         git_commit     *parent;
32         git_tree       *commit_tree;
33         git_tree       *parent_tree;
34
35         size_t addcount;
36         size_t delcount;
37         size_t filecount;
38 };
39
40 static git_repository *repo;
41
42 static const char *relpath = "";
43 static const char *repodir;
44
45 static char *name;
46 static char *stripped_name;
47 static char description[255];
48 static char cloneurl[1024];
49 static int hasreadme, haslicense;
50
51 void
52 commitinfo_free(struct commitinfo *ci)
53 {
54         if (!ci)
55                 return;
56
57         git_diff_stats_free(ci->stats);
58         git_diff_free(ci->diff);
59         git_tree_free(ci->commit_tree);
60         git_tree_free(ci->parent_tree);
61         git_commit_free(ci->commit);
62 }
63
64 struct commitinfo *
65 commitinfo_getbyoid(const git_oid *id)
66 {
67         struct commitinfo *ci;
68         git_diff_options opts;
69         int error;
70
71         if (!(ci = calloc(1, sizeof(struct commitinfo))))
72                 err(1, "calloc");
73
74         ci->id = id;
75         if (git_commit_lookup(&(ci->commit), repo, id))
76                 goto err;
77
78         git_oid_tostr(ci->oid, sizeof(ci->oid), git_commit_id(ci->commit));
79         git_oid_tostr(ci->parentoid, sizeof(ci->parentoid), git_commit_parent_id(ci->commit, 0));
80
81         ci->author = git_commit_author(ci->commit);
82         ci->summary = git_commit_summary(ci->commit);
83         ci->msg = git_commit_message(ci->commit);
84
85         if ((error = git_commit_tree(&(ci->commit_tree), ci->commit)))
86                 goto err;
87         if (!(error = git_commit_parent(&(ci->parent), ci->commit, 0))) {
88                 if ((error = git_commit_tree(&(ci->parent_tree), ci->parent)))
89                         goto err;
90         } else {
91                 ci->parent = NULL;
92                 ci->parent_tree = NULL;
93         }
94
95         git_diff_init_options(&opts, GIT_DIFF_OPTIONS_VERSION);
96         opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH;
97         if ((error = git_diff_tree_to_tree(&(ci->diff), repo, ci->parent_tree, ci->commit_tree, &opts)))
98                 goto err;
99         if (git_diff_get_stats(&(ci->stats), ci->diff))
100                 goto err;
101
102         ci->addcount = git_diff_stats_insertions(ci->stats);
103         ci->delcount = git_diff_stats_deletions(ci->stats);
104         ci->filecount = git_diff_stats_files_changed(ci->stats);
105
106         return ci;
107
108 err:
109         commitinfo_free(ci);
110         free(ci);
111
112         return NULL;
113 }
114
115 FILE *
116 efopen(const char *name, const char *flags)
117 {
118         FILE *fp;
119
120         if (!(fp = fopen(name, flags)))
121                 err(1, "fopen");
122
123         return fp;
124 }
125
126 /* Escape characters below as HTML 2.0 / XML 1.0. */
127 void
128 xmlencode(FILE *fp, const char *s, size_t len)
129 {
130         size_t i;
131
132         for (i = 0; *s && i < len; s++, i++) {
133                 switch(*s) {
134                 case '<':  fputs("&lt;",   fp); break;
135                 case '>':  fputs("&gt;",   fp); break;
136                 case '\'': fputs("&apos;", fp); break;
137                 case '&':  fputs("&amp;",  fp); break;
138                 case '"':  fputs("&quot;", fp); break;
139                 default:   fputc(*s, fp);
140                 }
141         }
142 }
143
144 /* Some implementations of dirname(3) return a pointer to a static
145  * internal buffer (OpenBSD). Others modify the contents of `path` (POSIX).
146  * This is a wrapper function that is compatible with both versions.
147  * The program will error out if dirname(3) failed, this can only happen
148  * with the OpenBSD version. */
149 char *
150 xdirname(const char *path)
151 {
152         char *p, *b;
153
154         if (!(p = strdup(path)))
155                 err(1, "strdup");
156         if (!(b = dirname(p)))
157                 err(1, "dirname");
158         if (!(b = strdup(b)))
159                 err(1, "strdup");
160         free(p);
161
162         return b;
163 }
164
165 /* Some implementations of basename(3) return a pointer to a static
166  * internal buffer (OpenBSD). Others modify the contents of `path` (POSIX).
167  * This is a wrapper function that is compatible with both versions.
168  * The program will error out if basename(3) failed, this can only happen
169  * with the OpenBSD version. */
170 char *
171 xbasename(const char *path)
172 {
173         char *p, *b;
174
175         if (!(p = strdup(path)))
176                 err(1, "strdup");
177         if (!(b = basename(p)))
178                 err(1, "basename");
179         if (!(b = strdup(b)))
180                 err(1, "strdup");
181         free(p);
182
183         return b;
184 }
185
186 int
187 mkdirp(const char *path)
188 {
189         char tmp[PATH_MAX], *p;
190
191         if (strlcpy(tmp, path, sizeof(tmp)) >= sizeof(tmp))
192                 errx(1, "path truncated: '%s'", path);
193         for (p = tmp + (tmp[0] == '/'); *p; p++) {
194                 if (*p != '/')
195                         continue;
196                 *p = '\0';
197                 if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
198                         return -1;
199                 *p = '/';
200         }
201         if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
202                 return -1;
203         return 0;
204 }
205
206 void
207 printtimeformat(FILE *fp, const git_time *intime, const char *fmt)
208 {
209         struct tm *intm;
210         time_t t;
211         char out[32];
212
213         t = (time_t) intime->time + (intime->offset * 60);
214         intm = gmtime(&t);
215         strftime(out, sizeof(out), fmt, intm);
216         fputs(out, fp);
217 }
218
219 void
220 printtimez(FILE *fp, const git_time *intime)
221 {
222         printtimeformat(fp, intime, "%Y-%m-%dT%H:%M:%SZ");
223 }
224
225 void
226 printtime(FILE *fp, const git_time *intime)
227 {
228         printtimeformat(fp, intime, "%a %b %e %T %Y");
229 }
230
231 void
232 printtimeshort(FILE *fp, const git_time *intime)
233 {
234         printtimeformat(fp, intime, "%Y-%m-%d %H:%M");
235 }
236
237 int
238 writeheader(FILE *fp)
239 {
240         fputs("<!DOCTYPE html>\n"
241                 "<html dir=\"ltr\" lang=\"en\">\n<head>\n"
242                 "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
243                 "<meta http-equiv=\"Content-Language\" content=\"en\" />\n<title>", fp);
244         xmlencode(fp, stripped_name, strlen(stripped_name));
245         if (description[0])
246                 fputs(" - ", fp);
247         xmlencode(fp, description, strlen(description));
248         fprintf(fp, "</title>\n<link rel=\"icon\" type=\"image/png\" href=\"%sfavicon.png\" />\n", relpath);
249         fprintf(fp, "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"%s Atom Feed\" href=\"%satom.xml\" />\n",
250                 name, relpath);
251         fprintf(fp, "<link rel=\"stylesheet\" type=\"text/css\" href=\"%sstyle.css\" />\n", relpath);
252         fputs("</head>\n<body>\n<table><tr><td>", fp);
253         fprintf(fp, "<a href=\"../%s\"><img src=\"%slogo.png\" alt=\"\" width=\"32\" height=\"32\" /></a>",
254                 relpath, relpath);
255         fputs("</td><td><h1>", fp);
256         xmlencode(fp, stripped_name, strlen(stripped_name));
257         fputs("</h1><span class=\"desc\">", fp);
258         xmlencode(fp, description, strlen(description));
259         fputs("</span></td></tr>", fp);
260         if (cloneurl[0]) {
261                 fputs("<tr class=\"url\"><td></td><td>git clone <a href=\"", fp);
262                 xmlencode(fp, cloneurl, strlen(cloneurl));
263                 fputs("\">", fp);
264                 xmlencode(fp, cloneurl, strlen(cloneurl));
265                 fputs("</a></td></tr>", fp);
266         }
267         fputs("<tr><td></td><td>\n", fp);
268         fprintf(fp, "<a href=\"%slog.html\">Log</a> | ", relpath);
269         fprintf(fp, "<a href=\"%sfiles.html\">Files</a> | ", relpath);
270         fprintf(fp, "<a href=\"%srefs.html\">Refs</a>", relpath);
271         if (hasreadme)
272                 fprintf(fp, " | <a href=\"%sfile/README.html\">README</a>", relpath);
273         if (haslicense)
274                 fprintf(fp, " | <a href=\"%sfile/LICENSE.html\">LICENSE</a>", relpath);
275         fputs("</td></tr></table>\n<hr/>\n<div id=\"content\">\n", fp);
276
277         return 0;
278 }
279
280 int
281 writefooter(FILE *fp)
282 {
283         return !fputs("</div>\n</body>\n</html>\n", fp);
284 }
285
286 int
287 writeblobhtml(FILE *fp, const git_blob *blob)
288 {
289         off_t i;
290         size_t n = 0;
291         char *nfmt = "<a href=\"#l%d\" id=\"l%d\">%d</a>\n";
292         const char *s = git_blob_rawcontent(blob);
293         git_off_t len = git_blob_rawsize(blob);
294
295         fputs("<table id=\"blob\"><tr><td class=\"num\"><pre>\n", fp);
296
297         if (len) {
298                 n++;
299                 fprintf(fp, nfmt, n, n, n);
300                 for (i = 0; i < len - 1; i++) {
301                         if (s[i] == '\n') {
302                                 n++;
303                                 fprintf(fp, nfmt, n, n, n);
304                         }
305                 }
306         }
307
308         fputs("</pre></td><td><pre>\n", fp);
309         xmlencode(fp, s, (size_t)len);
310         fputs("</pre></td></tr></table>\n", fp);
311
312         return n;
313 }
314
315 void
316 printcommit(FILE *fp, struct commitinfo *ci)
317 {
318         fprintf(fp, "<b>commit</b> <a href=\"%scommit/%s.html\">%s</a>\n",
319                 relpath, ci->oid, ci->oid);
320
321         if (ci->parentoid[0])
322                 fprintf(fp, "<b>parent</b> <a href=\"%scommit/%s.html\">%s</a>\n",
323                         relpath, ci->parentoid, ci->parentoid);
324
325         if (ci->author) {
326                 fputs("<b>Author:</b> ", fp);
327                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
328                 fputs(" &lt;<a href=\"mailto:", fp);
329                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
330                 fputs("\">", fp);
331                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
332                 fputs("</a>&gt;\n<b>Date:</b>   ", fp);
333                 printtime(fp, &(ci->author->when));
334                 fputc('\n', fp);
335         }
336         if (ci->msg) {
337                 fputc('\n', fp);
338                 xmlencode(fp, ci->msg, strlen(ci->msg));
339                 fputc('\n', fp);
340         }
341 }
342
343 void
344 printshowfile(FILE *fp, struct commitinfo *ci)
345 {
346         const git_diff_delta *delta;
347         const git_diff_hunk *hunk;
348         const git_diff_line *line;
349         git_patch *patch;
350         git_buf statsbuf;
351         size_t ndeltas, nhunks, nhunklines;
352         size_t i, j, k;
353
354         printcommit(fp, ci);
355
356         memset(&statsbuf, 0, sizeof(statsbuf));
357
358         /* diff stat */
359         if (ci->stats &&
360             !git_diff_stats_to_buf(&statsbuf, ci->stats,
361                                    GIT_DIFF_STATS_FULL | GIT_DIFF_STATS_SHORT, 80)) {
362                 if (statsbuf.ptr && statsbuf.ptr[0]) {
363                         fputs("<b>Diffstat:</b>\n", fp);
364                         xmlencode(fp, statsbuf.ptr, strlen(statsbuf.ptr));
365                 }
366         }
367
368         fputs("<hr/>", fp);
369
370         ndeltas = git_diff_num_deltas(ci->diff);
371         for (i = 0; i < ndeltas; i++) {
372                 if (git_patch_from_diff(&patch, ci->diff, i)) {
373                         git_patch_free(patch);
374                         break;
375                 }
376
377                 delta = git_patch_get_delta(patch);
378                 fprintf(fp, "<b>diff --git a/<a href=\"%sfile/%s.html\">%s</a> b/<a href=\"%sfile/%s.html\">%s</a></b>\n",
379                         relpath, delta->old_file.path, delta->old_file.path,
380                         relpath, delta->new_file.path, delta->new_file.path);
381
382                 /* check binary data */
383                 if (delta->flags & GIT_DIFF_FLAG_BINARY) {
384                         fputs("Binary files differ\n", fp);
385                         git_patch_free(patch);
386                         continue;
387                 }
388
389                 nhunks = git_patch_num_hunks(patch);
390                 for (j = 0; j < nhunks; j++) {
391                         if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
392                                 break;
393
394                         fprintf(fp, "<a href=\"#h%zu\" id=\"h%zu\" class=\"h\">", j, j);
395                         xmlencode(fp, hunk->header, hunk->header_len);
396                         fputs("</a>", fp);
397
398                         for (k = 0; ; k++) {
399                                 if (git_patch_get_line_in_hunk(&line, patch, j, k))
400                                         break;
401                                 if (line->old_lineno == -1)
402                                         fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"i\">+",
403                                                 j, k, j, k);
404                                 else if (line->new_lineno == -1)
405                                         fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"d\">-",
406                                                 j, k, j, k);
407                                 else
408                                         fputc(' ', fp);
409                                 xmlencode(fp, line->content, line->content_len);
410                                 if (line->old_lineno == -1 || line->new_lineno == -1)
411                                         fputs("</a>", fp);
412                         }
413                 }
414                 git_patch_free(patch);
415         }
416         git_buf_free(&statsbuf);
417
418         return;
419 }
420
421 int
422 writelog(FILE *fp, const git_oid *oid)
423 {
424         struct commitinfo *ci;
425         git_revwalk *w = NULL;
426         git_oid id;
427         size_t len;
428         char path[PATH_MAX];
429         FILE *fpfile;
430         int r;
431
432         git_revwalk_new(&w, repo);
433         git_revwalk_push(w, oid);
434         git_revwalk_sorting(w, GIT_SORT_TIME);
435         git_revwalk_simplify_first_parent(w);
436
437         fputs("<table id=\"log\"><thead>\n<tr><td>Date</td><td>Commit message</td>"
438                   "<td>Author</td><td>Files</td><td class=\"num\">+</td>"
439                   "<td class=\"num\">-</td></tr>\n</thead><tbody>\n", fp);
440
441         while (!git_revwalk_next(&id, w)) {
442                 relpath = "";
443
444                 if (!(ci = commitinfo_getbyoid(&id)))
445                         break;
446
447                 fputs("<tr><td>", fp);
448                 if (ci->author)
449                         printtimeshort(fp, &(ci->author->when));
450                 fputs("</td><td>", fp);
451                 if (ci->summary) {
452                         fprintf(fp, "<a href=\"%scommit/%s.html\">", relpath, ci->oid);
453                         if ((len = strlen(ci->summary)) > summarylen) {
454                                 xmlencode(fp, ci->summary, summarylen - 1);
455                                 fputs("…", fp);
456                         } else {
457                                 xmlencode(fp, ci->summary, len);
458                         }
459                         fputs("</a>", fp);
460                 }
461                 fputs("</td><td>", fp);
462                 if (ci->author)
463                         xmlencode(fp, ci->author->name, strlen(ci->author->name));
464                 fputs("</td><td class=\"num\">", fp);
465                 fprintf(fp, "%zu", ci->filecount);
466                 fputs("</td><td class=\"num\">", fp);
467                 fprintf(fp, "+%zu", ci->addcount);
468                 fputs("</td><td class=\"num\">", fp);
469                 fprintf(fp, "-%zu", ci->delcount);
470                 fputs("</td></tr>\n", fp);
471
472                 relpath = "../";
473
474                 r = snprintf(path, sizeof(path), "commit/%s.html", ci->oid);
475                 if (r == -1 || (size_t)r >= sizeof(path))
476                         errx(1, "path truncated: 'commit/%s.html'", ci->oid);
477
478                 /* check if file exists if so skip it */
479                 if (access(path, F_OK)) {
480                         fpfile = efopen(path, "w");
481                         writeheader(fpfile);
482                         fputs("<pre>", fpfile);
483                         printshowfile(fpfile, ci);
484                         fputs("</pre>\n", fpfile);
485                         writefooter(fpfile);
486                         fclose(fpfile);
487                 }
488                 commitinfo_free(ci);
489         }
490         fputs("</tbody></table>", fp);
491
492         git_revwalk_free(w);
493
494         relpath = "";
495
496         return 0;
497 }
498
499 void
500 printcommitatom(FILE *fp, struct commitinfo *ci)
501 {
502         fputs("<entry>\n", fp);
503
504         fprintf(fp, "<id>%s</id>\n", ci->oid);
505         if (ci->author) {
506                 fputs("<updated>", fp);
507                 printtimez(fp, &(ci->author->when));
508                 fputs("</updated>\n", fp);
509         }
510         if (ci->summary) {
511                 fputs("<title type=\"text\">", fp);
512                 xmlencode(fp, ci->summary, strlen(ci->summary));
513                 fputs("</title>\n", fp);
514         }
515         fprintf(fp, "<link rel=\"alternate\" type=\"text/html\" href=\"commit/%s.html\" />",
516                 ci->oid);
517
518         if (ci->author) {
519                 fputs("<author><name>", fp);
520                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
521                 fputs("</name>\n<email>", fp);
522                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
523                 fputs("</email>\n</author>\n", fp);
524         }
525
526         fputs("<content type=\"text\">", fp);
527         fprintf(fp, "commit %s\n", ci->oid);
528         if (ci->parentoid[0])
529                 fprintf(fp, "parent %s\n", ci->parentoid);
530         if (ci->author) {
531                 fputs("Author: ", fp);
532                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
533                 fputs(" &lt;", fp);
534                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
535                 fputs("&gt;\nDate:   ", fp);
536                 printtime(fp, &(ci->author->when));
537                 fputc('\n', fp);
538         }
539         if (ci->msg) {
540                 fputc('\n', fp);
541                 xmlencode(fp, ci->msg, strlen(ci->msg));
542         }
543         fputs("\n</content>\n", fp);
544
545         fputs("</entry>\n", fp);
546 }
547
548 int
549 writeatom(FILE *fp)
550 {
551         struct commitinfo *ci;
552         git_revwalk *w = NULL;
553         git_oid id;
554         size_t i, m = 100; /* max */
555
556         fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
557               "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n<title>", fp);
558         xmlencode(fp, stripped_name, strlen(stripped_name));
559         fputs(", branch HEAD</title>\n<subtitle>", fp);
560         xmlencode(fp, description, strlen(description));
561         fputs("</subtitle>\n", fp);
562
563         git_revwalk_new(&w, repo);
564         git_revwalk_push_head(w);
565         git_revwalk_sorting(w, GIT_SORT_TIME);
566         git_revwalk_simplify_first_parent(w);
567
568         for (i = 0; i < m && !git_revwalk_next(&id, w); i++) {
569                 if (!(ci = commitinfo_getbyoid(&id)))
570                         break;
571                 printcommitatom(fp, ci);
572                 commitinfo_free(ci);
573         }
574         git_revwalk_free(w);
575
576         fputs("</feed>", fp);
577
578         return 0;
579 }
580
581 int
582 writeblob(git_object *obj, const char *fpath, const char *filename, git_off_t filesize)
583 {
584         char tmp[PATH_MAX] = "";
585         char *d;
586         const char *p;
587         int lc = 0;
588         FILE *fp;
589
590         d = xdirname(fpath);
591         if (mkdirp(d)) {
592                 free(d);
593                 return -1;
594         }
595         free(d);
596
597         p = fpath;
598         while (*p) {
599                 if (*p == '/' && strlcat(tmp, "../", sizeof(tmp)) >= sizeof(tmp))
600                         errx(1, "path truncated: '../%s'", tmp);
601                 p++;
602         }
603         relpath = tmp;
604
605         fp = efopen(fpath, "w");
606         writeheader(fp);
607         fputs("<p> ", fp);
608         xmlencode(fp, filename, strlen(filename));
609         fprintf(fp, " (%juB)", (uintmax_t)filesize);
610         fputs("</p><hr/>", fp);
611
612         if (git_blob_is_binary((git_blob *)obj)) {
613                 fputs("<p>Binary file</p>\n", fp);
614         } else {
615                 lc = writeblobhtml(fp, (git_blob *)obj);
616                 if (ferror(fp))
617                         err(1, "fwrite");
618         }
619         writefooter(fp);
620         fclose(fp);
621
622         relpath = "";
623
624         return lc;
625 }
626
627 const char *
628 filemode(git_filemode_t m)
629 {
630         static char mode[11];
631
632         memset(mode, '-', sizeof(mode) - 1);
633         mode[10] = '\0';
634
635         if (S_ISREG(m))
636                 mode[0] = '-';
637         else if (S_ISBLK(m))
638                 mode[0] = 'b';
639         else if (S_ISCHR(m))
640                 mode[0] = 'c';
641         else if (S_ISDIR(m))
642                 mode[0] = 'd';
643         else if (S_ISFIFO(m))
644                 mode[0] = 'p';
645         else if (S_ISLNK(m))
646                 mode[0] = 'l';
647         else if (S_ISSOCK(m))
648                 mode[0] = 's';
649         else
650                 mode[0] = '?';
651
652         if (m & S_IRUSR) mode[1] = 'r';
653         if (m & S_IWUSR) mode[2] = 'w';
654         if (m & S_IXUSR) mode[3] = 'x';
655         if (m & S_IRGRP) mode[4] = 'r';
656         if (m & S_IWGRP) mode[5] = 'w';
657         if (m & S_IXGRP) mode[6] = 'x';
658         if (m & S_IROTH) mode[7] = 'r';
659         if (m & S_IWOTH) mode[8] = 'w';
660         if (m & S_IXOTH) mode[9] = 'x';
661
662         if (m & S_ISUID) mode[3] = (mode[3] == 'x') ? 's' : 'S';
663         if (m & S_ISGID) mode[6] = (mode[6] == 'x') ? 's' : 'S';
664         if (m & S_ISVTX) mode[9] = (mode[9] == 'x') ? 't' : 'T';
665
666         return mode;
667 }
668
669 int
670 writefilestree(FILE *fp, git_tree *tree, const char *branch, const char *path)
671 {
672         const git_tree_entry *entry = NULL;
673         const char *entryname;
674         char filepath[PATH_MAX], entrypath[PATH_MAX];
675         git_object *obj = NULL;
676         git_off_t filesize;
677         size_t count, i;
678         int lc, r, ret;
679
680         count = git_tree_entrycount(tree);
681         for (i = 0; i < count; i++) {
682                 if (!(entry = git_tree_entry_byindex(tree, i)) ||
683                     git_tree_entry_to_object(&obj, repo, entry))
684                         return -1;
685                 entryname = git_tree_entry_name(entry);
686                 r = snprintf(entrypath, sizeof(entrypath), "%s%s%s",
687                          path, path[0] ? "/" : "", entryname);
688                 if (r == -1 || (size_t)r >= sizeof(entrypath))
689                         errx(1, "path truncated: '%s%s%s'",
690                                 path, path[0] ? "/" : "", entryname);
691                 switch (git_object_type(obj)) {
692                 case GIT_OBJ_BLOB:
693                         break;
694                 case GIT_OBJ_TREE:
695                         /* NOTE: recurses */
696                         ret = writefilestree(fp, (git_tree *)obj, branch,
697                                              entrypath);
698                         git_object_free(obj);
699                         if (ret)
700                                 return ret;
701                         continue;
702                 default:
703                         git_object_free(obj);
704                         continue;
705                 }
706
707                 r = snprintf(filepath, sizeof(filepath), "file/%s%s%s.html",
708                          path, path[0] ? "/" : "", entryname);
709                 if (r == -1 || (size_t)r >= sizeof(filepath))
710                         errx(1, "path truncated: 'file/%s%s%s.html'",
711                                 path, path[0] ? "/" : "", entryname);
712
713                 filesize = git_blob_rawsize((git_blob *)obj);
714
715                 lc = writeblob(obj, filepath, entryname, filesize);
716
717                 fputs("<tr><td>", fp);
718                 fputs(filemode(git_tree_entry_filemode(entry)), fp);
719                 fprintf(fp, "</td><td><a href=\"%s%s\">", relpath, filepath);
720                 xmlencode(fp, entrypath, strlen(entrypath));
721                 fputs("</a></td><td class=\"num\">", fp);
722                 if (showlinecount && lc > 0)
723                         fprintf(fp, "%dL", lc);
724                 else
725                         fprintf(fp, "%juB", (uintmax_t)filesize);
726                 fputs("</td></tr>\n", fp);
727         }
728
729         return 0;
730 }
731
732 int
733 writefiles(FILE *fp, const git_oid *id, const char *branch)
734 {
735         git_tree *tree = NULL;
736         git_commit *commit = NULL;
737         int ret = -1;
738
739         fputs("<table id=\"files\"><thead>\n<tr>"
740               "<td>Mode</td><td>Name</td><td class=\"num\">Size</td>"
741               "</tr>\n</thead><tbody>\n", fp);
742
743         if (git_commit_lookup(&commit, repo, id) ||
744             git_commit_tree(&tree, commit))
745                 goto err;
746         ret = writefilestree(fp, tree, branch, "");
747
748 err:
749         fputs("</tbody></table>", fp);
750
751         git_commit_free(commit);
752         git_tree_free(tree);
753
754         return ret;
755 }
756
757 int
758 refs_cmp(const void *v1, const void *v2)
759 {
760         git_reference *r1 = (*(git_reference **)v1);
761         git_reference *r2 = (*(git_reference **)v2);
762         int t1, t2;
763
764         t1 = git_reference_is_branch(r1);
765         t2 = git_reference_is_branch(r2);
766
767         if (t1 != t2)
768                 return t1 - t2;
769
770         return strcmp(git_reference_shorthand(r1),
771                       git_reference_shorthand(r2));
772 }
773
774 int
775 writerefs(FILE *fp)
776 {
777         struct commitinfo *ci;
778         const git_oid *id = NULL;
779         git_object *obj = NULL;
780         git_reference *dref = NULL, *r, *ref = NULL;
781         git_reference_iterator *it = NULL;
782         git_reference **refs = NULL;
783         size_t count, i, j, refcount = 0;
784         const char *titles[] = { "Branches", "Tags" };
785         const char *ids[] = { "branches", "tags" };
786         const char *name;
787
788         if (git_reference_iterator_new(&it, repo))
789                 return -1;
790
791         for (refcount = 0; !git_reference_next(&ref, it); refcount++) {
792                 if (!(refs = reallocarray(refs, refcount + 1, sizeof(git_reference *))))
793                         err(1, "realloc");
794                 refs[refcount] = ref;
795         }
796         git_reference_iterator_free(it);
797
798         /* sort by type then shorthand name */
799         qsort(refs, refcount, sizeof(git_reference *), refs_cmp);
800
801         for (j = 0; j < 2; j++) {
802                 for (i = 0, count = 0; i < refcount; i++) {
803                         if (!(git_reference_is_branch(refs[i]) && j == 0) &&
804                             !(git_reference_is_tag(refs[i]) && j == 1))
805                                 continue;
806
807                         switch (git_reference_type(refs[i])) {
808                         case GIT_REF_SYMBOLIC:
809                                 if (git_reference_resolve(&dref, refs[i]))
810                                         goto err;
811                                 r = dref;
812                                 break;
813                         case GIT_REF_OID:
814                                 r = refs[i];
815                                 break;
816                         default:
817                                 continue;
818                         }
819                         if (!(id = git_reference_target(r)))
820                                 goto err;
821                         if (git_reference_peel(&obj, r, GIT_OBJ_ANY))
822                                 goto err;
823                         if (!(id = git_object_id(obj)))
824                                 goto err;
825                         if (!(ci = commitinfo_getbyoid(id)))
826                                 break;
827
828                         /* print header if it has an entry (first). */
829                         if (++count == 1) {
830                                 fprintf(fp, "<h2>%s</h2><table id=\"%s\"><thead>\n<tr><td>Name</td>"
831                                       "<td>Last commit date</td><td>Author</td>\n</tr>\n</thead><tbody>\n",
832                                       titles[j], ids[j]);
833                         }
834
835                         relpath = "";
836                         name = git_reference_shorthand(r);
837
838                         fputs("<tr><td>", fp);
839                         xmlencode(fp, name, strlen(name));
840                         fputs("</td><td>", fp);
841                         if (ci->author)
842                                 printtimeshort(fp, &(ci->author->when));
843                         fputs("</td><td>", fp);
844                         if (ci->author)
845                                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
846                         fputs("</td></tr>\n", fp);
847
848                         relpath = "../";
849
850                         commitinfo_free(ci);
851                         git_object_free(obj);
852                         obj = NULL;
853                         git_reference_free(dref);
854                         dref = NULL;
855                 }
856                 /* table footer */
857                 if (count)
858                         fputs("</tbody></table><br/>", fp);
859         }
860
861 err:
862         git_object_free(obj);
863         git_reference_free(dref);
864
865         for (i = 0; i < refcount; i++)
866                 git_reference_free(refs[i]);
867         free(refs);
868
869         return 0;
870 }
871
872 int
873 main(int argc, char *argv[])
874 {
875         git_object *obj = NULL;
876         const git_oid *head = NULL;
877         const git_error *e = NULL;
878         FILE *fp, *fpread;
879         char path[PATH_MAX], *p;
880         int r, status;
881
882         if (argc != 2) {
883                 fprintf(stderr, "%s <repodir>\n", argv[0]);
884                 return 1;
885         }
886         repodir = argv[1];
887
888         git_libgit2_init();
889
890         if ((status = git_repository_open_ext(&repo, repodir,
891                 GIT_REPOSITORY_OPEN_NO_SEARCH, NULL)) < 0) {
892                 e = giterr_last();
893                 fprintf(stderr, "error %d/%d: %s\n", status, e->klass, e->message);
894                 return status;
895         }
896
897         /* find HEAD */
898         if (git_revparse_single(&obj, repo, "HEAD"))
899                 return 1;
900         head = git_object_id(obj);
901         git_object_free(obj);
902
903         /* use directory name as name */
904         name = xbasename(repodir);
905
906         /* strip .git suffix */
907         if (!(stripped_name = strdup(name)))
908                 err(1, "strdup");
909         if ((p = strrchr(stripped_name, '.')))
910                 if (!strcmp(p, ".git"))
911                         *p = '\0';
912
913         /* read description or .git/description */
914         r = snprintf(path, sizeof(path), "%s%s%s",
915                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "description");
916         if (r == -1 || (size_t)r >= sizeof(path))
917                 errx(1, "path truncated: '%s%s%s'",
918                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "description");
919         if (!(fpread = fopen(path, "r"))) {
920                 r = snprintf(path, sizeof(path), "%s%s%s",
921                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/description");
922                 if (r == -1 || (size_t)r >= sizeof(path))
923                         errx(1, "path truncated: '%s%s%s'",
924                                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/description");
925                 fpread = fopen(path, "r");
926         }
927         if (fpread) {
928                 if (!fgets(description, sizeof(description), fpread))
929                         description[0] = '\0';
930                 fclose(fpread);
931         }
932
933         /* read url or .git/url */
934         r = snprintf(path, sizeof(path), "%s%s%s",
935                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "url");
936         if (r == -1 || (size_t)r >= sizeof(path))
937                 errx(1, "path truncated: '%s%s%s'",
938                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "url");
939         if (!(fpread = fopen(path, "r"))) {
940                 r = snprintf(path, sizeof(path), "%s%s%s",
941                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/url");
942                 if (r == -1 || (size_t)r >= sizeof(path))
943                         errx(1, "path truncated: '%s%s%s'",
944                                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/url");
945                 fpread = fopen(path, "r");
946         }
947         if (fpread) {
948                 if (!fgets(cloneurl, sizeof(cloneurl), fpread))
949                         cloneurl[0] = '\0';
950                 cloneurl[strcspn(cloneurl, "\n")] = '\0';
951                 fclose(fpread);
952         }
953
954         /* check LICENSE */
955         haslicense = !git_revparse_single(&obj, repo, "HEAD:LICENSE");
956         git_object_free(obj);
957         /* check README */
958         hasreadme = !git_revparse_single(&obj, repo, "HEAD:README");
959         git_object_free(obj);
960
961         /* log for HEAD */
962         fp = efopen("log.html", "w");
963         relpath = "";
964         writeheader(fp);
965         mkdir("commit", 0755);
966         writelog(fp, head);
967         writefooter(fp);
968         fclose(fp);
969
970         /* files for HEAD */
971         fp = efopen("files.html", "w");
972         writeheader(fp);
973         writefiles(fp, head, "HEAD");
974         writefooter(fp);
975         fclose(fp);
976
977         /* summary page with branches and tags */
978         fp = efopen("refs.html", "w");
979         writeheader(fp);
980         writerefs(fp);
981         writefooter(fp);
982         fclose(fp);
983
984         /* Atom feed */
985         fp = efopen("atom.xml", "w");
986         writeatom(fp);
987         fclose(fp);
988
989         /* cleanup */
990         git_repository_free(repo);
991         git_libgit2_shutdown();
992
993         return 0;
994 }