]> git.armaanb.net Git - stagit.git/blob - stagit.c
atom: add newline after date and before message
[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, "basename");
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         strlcpy(tmp, path, sizeof(tmp));
192         for (p = tmp + (tmp[0] == '/'); *p; p++) {
193                 if (*p != '/')
194                         continue;
195                 *p = '\0';
196                 if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
197                         return -1;
198                 *p = '/';
199         }
200         if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
201                 return -1;
202         return 0;
203 }
204
205 void
206 printtimeformat(FILE *fp, const git_time *intime, const char *fmt)
207 {
208         struct tm *intm;
209         time_t t;
210         char out[32];
211
212         t = (time_t) intime->time + (intime->offset * 60);
213         intm = gmtime(&t);
214         strftime(out, sizeof(out), fmt, intm);
215         fputs(out, fp);
216 }
217
218 void
219 printtimez(FILE *fp, const git_time *intime)
220 {
221         printtimeformat(fp, intime, "%Y-%m-%dT%H:%M:%SZ");
222 }
223
224 void
225 printtime(FILE *fp, const git_time *intime)
226 {
227         printtimeformat(fp, intime, "%a %b %e %T %Y");
228 }
229
230 void
231 printtimeshort(FILE *fp, const git_time *intime)
232 {
233         printtimeformat(fp, intime, "%Y-%m-%d %H:%M");
234 }
235
236 int
237 writeheader(FILE *fp)
238 {
239         fputs("<!DOCTYPE HTML>"
240                 "<html dir=\"ltr\" lang=\"en\">\n<head>\n"
241                 "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
242                 "<meta http-equiv=\"Content-Language\" content=\"en\" />\n<title>", fp);
243         xmlencode(fp, stripped_name, strlen(stripped_name));
244         if (description[0])
245                 fputs(" - ", fp);
246         xmlencode(fp, description, strlen(description));
247         fprintf(fp, "</title>\n<link rel=\"icon\" type=\"image/png\" href=\"%sfavicon.png\" />\n", relpath);
248         fprintf(fp, "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"%s Atom Feed\" href=\"%satom.xml\" />\n",
249                 name, relpath);
250         fprintf(fp, "<link rel=\"stylesheet\" type=\"text/css\" href=\"%sstyle.css\" />\n", relpath);
251         fputs("</head>\n<body>\n<table><tr><td>", fp);
252         fprintf(fp, "<a href=\"../%s\"><img src=\"%slogo.png\" alt=\"\" width=\"32\" height=\"32\" /></a>",
253                 relpath, relpath);
254         fputs("</td><td><h1>", fp);
255         xmlencode(fp, stripped_name, strlen(stripped_name));
256         fputs("</h1><span class=\"desc\">", fp);
257         xmlencode(fp, description, strlen(description));
258         fputs("</span></td></tr>", fp);
259         if (cloneurl[0]) {
260                 fputs("<tr class=\"url\"><td></td><td>git clone <a href=\"", fp);
261                 xmlencode(fp, cloneurl, strlen(cloneurl));
262                 fputs("\">", fp);
263                 xmlencode(fp, cloneurl, strlen(cloneurl));
264                 fputs("</a></td></tr>", fp);
265         }
266         fputs("<tr><td></td><td>\n", fp);
267         fprintf(fp, "<a href=\"%slog.html\">Log</a> | ", relpath);
268         fprintf(fp, "<a href=\"%sfiles.html\">Files</a> | ", relpath);
269         fprintf(fp, "<a href=\"%srefs.html\">Refs/branches</a>", relpath);
270         if (hasreadme)
271                 fprintf(fp, " | <a href=\"%sfile/README.html\">README</a>", relpath);
272         if (haslicense)
273                 fprintf(fp, " | <a href=\"%sfile/LICENSE.html\">LICENSE</a>", relpath);
274         fputs("</td></tr></table>\n<hr/>\n<div id=\"content\">\n", fp);
275
276         return 0;
277 }
278
279 int
280 writefooter(FILE *fp)
281 {
282         return !fputs("</div>\n</body>\n</html>\n", fp);
283 }
284
285 void
286 writeblobhtml(FILE *fp, const git_blob *blob)
287 {
288         off_t i;
289         size_t n = 1;
290         char *nfmt = "<a href=\"#l%d\" id=\"l%d\">%d</a>\n";
291         const char *s = git_blob_rawcontent(blob);
292         git_off_t len = git_blob_rawsize(blob);
293
294         fputs("<table id=\"blob\"><tr><td class=\"num\"><pre>\n", fp);
295
296         if (len) {
297                 fprintf(fp, nfmt, n, n, n);
298                 for (i = 0; i < len - 1; i++) {
299                         if (s[i] == '\n') {
300                                 n++;
301                                 fprintf(fp, nfmt, n, n, n);
302                         }
303                 }
304         }
305
306         fputs("</pre></td><td><pre>\n", fp);
307         xmlencode(fp, s, (size_t)len);
308         fputs("</pre></td></tr></table>\n", fp);
309 }
310
311 void
312 printcommit(FILE *fp, struct commitinfo *ci)
313 {
314         fprintf(fp, "<b>commit</b> <a href=\"%scommit/%s.html\">%s</a>\n",
315                 relpath, ci->oid, ci->oid);
316
317         if (ci->parentoid[0])
318                 fprintf(fp, "<b>parent</b> <a href=\"%scommit/%s.html\">%s</a>\n",
319                         relpath, ci->parentoid, ci->parentoid);
320
321         if (ci->author) {
322                 fputs("<b>Author:</b> ", fp);
323                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
324                 fputs(" &lt;<a href=\"mailto:", fp);
325                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
326                 fputs("\">", fp);
327                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
328                 fputs("</a>&gt;\n<b>Date:</b>   ", fp);
329                 printtime(fp, &(ci->author->when));
330                 fputc('\n', fp);
331         }
332         fputc('\n', fp);
333
334         if (ci->msg)
335                 xmlencode(fp, ci->msg, strlen(ci->msg));
336
337         fputc('\n', fp);
338 }
339
340 void
341 printshowfile(struct commitinfo *ci)
342 {
343         const git_diff_delta *delta;
344         const git_diff_hunk *hunk;
345         const git_diff_line *line;
346         git_patch *patch;
347         git_buf statsbuf;
348         size_t ndeltas, nhunks, nhunklines;
349         FILE *fp;
350         size_t i, j, k;
351         char path[PATH_MAX];
352
353         snprintf(path, sizeof(path), "commit/%s.html", ci->oid);
354         /* check if file exists if so skip it */
355         if (!access(path, F_OK))
356                 return;
357
358         fp = efopen(path, "w");
359         writeheader(fp);
360         fputs("<pre>\n", fp);
361         printcommit(fp, ci);
362
363         memset(&statsbuf, 0, sizeof(statsbuf));
364
365         /* diff stat */
366         if (ci->stats) {
367                 if (!git_diff_stats_to_buf(&statsbuf, ci->stats,
368                     GIT_DIFF_STATS_FULL | GIT_DIFF_STATS_SHORT, 80)) {
369                         if (statsbuf.ptr && statsbuf.ptr[0]) {
370                                 fputs("<b>Diffstat:</b>\n", fp);
371                                 fputs(statsbuf.ptr, fp);
372                         }
373                 }
374         }
375
376         fputs("<hr/>", fp);
377
378         ndeltas = git_diff_num_deltas(ci->diff);
379         for (i = 0; i < ndeltas; i++) {
380                 if (git_patch_from_diff(&patch, ci->diff, i)) {
381                         git_patch_free(patch);
382                         break;
383                 }
384
385                 delta = git_patch_get_delta(patch);
386                 fprintf(fp, "<b>diff --git a/<a href=\"%sfile/%s.html\">%s</a> b/<a href=\"%sfile/%s.html\">%s</a></b>\n",
387                         relpath, delta->old_file.path, delta->old_file.path,
388                         relpath, delta->new_file.path, delta->new_file.path);
389
390                 /* check binary data */
391                 if (delta->flags & GIT_DIFF_FLAG_BINARY) {
392                         fputs("Binary files differ\n", fp);
393                         git_patch_free(patch);
394                         continue;
395                 }
396
397                 nhunks = git_patch_num_hunks(patch);
398                 for (j = 0; j < nhunks; j++) {
399                         if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
400                                 break;
401
402                         fprintf(fp, "<a href=\"#h%zu\" id=\"h%zu\" class=\"h\">", j, j);
403                         xmlencode(fp, hunk->header, hunk->header_len);
404                         fputs("</a>", fp);
405
406                         for (k = 0; ; k++) {
407                                 if (git_patch_get_line_in_hunk(&line, patch, j, k))
408                                         break;
409                                 if (line->old_lineno == -1)
410                                         fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"i\">+",
411                                                 j, k, j, k);
412                                 else if (line->new_lineno == -1)
413                                         fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"d\">-",
414                                                 j, k, j, k);
415                                 else
416                                         fputc(' ', fp);
417                                 xmlencode(fp, line->content, line->content_len);
418                                 if (line->old_lineno == -1 || line->new_lineno == -1)
419                                         fputs("</a>", fp);
420                         }
421                 }
422                 git_patch_free(patch);
423         }
424         git_buf_free(&statsbuf);
425
426         fputs("</pre>\n", fp);
427         writefooter(fp);
428         fclose(fp);
429         return;
430 }
431
432 int
433 writelog(FILE *fp, const char *branch)
434 {
435         struct commitinfo *ci;
436         const git_oid *oid;
437         git_revwalk *w = NULL;
438         git_object *obj = NULL;
439         git_oid id;
440         size_t len;
441
442         mkdir("commit", 0755);
443
444         if (git_revparse_single(&obj, repo, branch))
445                 return -1;
446         oid = git_object_id(obj);
447
448         git_revwalk_new(&w, repo);
449         git_revwalk_push(w, oid);
450         git_revwalk_sorting(w, GIT_SORT_TIME);
451         git_revwalk_simplify_first_parent(w);
452
453         fputs("<table id=\"log\"><thead>\n<tr><td>Age</td><td>Commit message</td>"
454                   "<td>Author</td><td>Files</td><td class=\"num\">+</td>"
455                   "<td class=\"num\">-</td></tr>\n</thead><tbody>\n", fp);
456
457         while (!git_revwalk_next(&id, w)) {
458                 relpath = "";
459
460                 if (!(ci = commitinfo_getbyoid(&id)))
461                         break;
462
463                 fputs("<tr><td>", fp);
464                 if (ci->author)
465                         printtimeshort(fp, &(ci->author->when));
466                 fputs("</td><td>", fp);
467                 if (ci->summary) {
468                         fprintf(fp, "<a href=\"%scommit/%s.html\">", relpath, ci->oid);
469                         if ((len = strlen(ci->summary)) > summarylen) {
470                                 xmlencode(fp, ci->summary, summarylen - 1);
471                                 fputs("…", fp);
472                         } else {
473                                 xmlencode(fp, ci->summary, len);
474                         }
475                         fputs("</a>", fp);
476                 }
477                 fputs("</td><td>", fp);
478                 if (ci->author)
479                         xmlencode(fp, ci->author->name, strlen(ci->author->name));
480                 fputs("</td><td class=\"num\">", fp);
481                 fprintf(fp, "%zu", ci->filecount);
482                 fputs("</td><td class=\"num\">", fp);
483                 fprintf(fp, "+%zu", ci->addcount);
484                 fputs("</td><td class=\"num\">", fp);
485                 fprintf(fp, "-%zu", ci->delcount);
486                 fputs("</td></tr>\n", fp);
487
488                 relpath = "../";
489                 printshowfile(ci);
490
491                 commitinfo_free(ci);
492         }
493         fputs("</tbody></table>", fp);
494
495         git_revwalk_free(w);
496         git_object_free(obj);
497
498         relpath = "";
499
500         return 0;
501 }
502
503 void
504 printcommitatom(FILE *fp, struct commitinfo *ci)
505 {
506         fputs("<entry>\n", fp);
507
508         fprintf(fp, "<id>%s</id>\n", ci->oid);
509         if (ci->author) {
510                 fputs("<updated>", fp);
511                 printtimez(fp, &(ci->author->when));
512                 fputs("</updated>\n", fp);
513         }
514         if (ci->summary) {
515                 fputs("<title type=\"text\">", fp);
516                 xmlencode(fp, ci->summary, strlen(ci->summary));
517                 fputs("</title>\n", fp);
518         }
519
520         fputs("<content type=\"text\">", fp);
521         fprintf(fp, "commit %s\n", ci->oid);
522         if (ci->parentoid[0])
523                 fprintf(fp, "parent %s\n", ci->parentoid);
524         if (ci->author) {
525                 fputs("Author: ", fp);
526                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
527                 fputs(" &lt;", fp);
528                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
529                 fputs("&gt;\nDate:   ", fp);
530                 printtime(fp, &(ci->author->when));
531                 fputc('\n', fp);
532         }
533         if (ci->msg) {
534                 fputc('\n', fp);
535                 xmlencode(fp, ci->msg, strlen(ci->msg));
536         }
537         fputs("\n</content>\n", fp);
538         if (ci->author) {
539                 fputs("<author><name>", fp);
540                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
541                 fputs("</name>\n<email>", fp);
542                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
543                 fputs("</email>\n</author>\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 *filename, git_off_t filesize)
583 {
584         char fpath[PATH_MAX];
585         char tmp[PATH_MAX] = "";
586         char *d, *p;
587         FILE *fp;
588
589         snprintf(fpath, sizeof(fpath), "file/%s.html", filename);
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 == '/')
600                         strlcat(tmp, "../", sizeof(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                 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 0;
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 *filename;
674         char filepath[PATH_MAX];
675         git_object *obj = NULL;
676         git_off_t filesize;
677         size_t count, i;
678         int 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                 filename = git_tree_entry_name(entry);
686                 switch (git_object_type(obj)) {
687                 case GIT_OBJ_BLOB:
688                         break;
689                 case GIT_OBJ_TREE:
690                         /* NOTE: recurses */
691                         ret = writefilestree(fp, (git_tree *)obj, branch,
692                                              filename);
693                         git_object_free(obj);
694                         if (ret)
695                                 return ret;
696                         continue;
697                 default:
698                         git_object_free(obj);
699                         continue;
700                 }
701                 if (path[0]) {
702                         snprintf(filepath, sizeof(filepath), "%s/%s",
703                                  path, filename);
704                         filename = filepath;
705                 }
706                 filesize = git_blob_rawsize((git_blob *)obj);
707
708                 fputs("<tr><td>", fp);
709                 fprintf(fp, "%s", filemode(git_tree_entry_filemode(entry)));
710                 fprintf(fp, "</td><td><a href=\"%sfile/", relpath);
711                 xmlencode(fp, filename, strlen(filename));
712                 fputs(".html\">", fp);
713                 xmlencode(fp, filename, strlen(filename));
714                 fputs("</a></td><td class=\"num\">", fp);
715                 fprintf(fp, "%ju", (uintmax_t)filesize);
716                 fputs("</td></tr>\n", fp);
717
718                 writeblob(obj, filename, filesize);
719         }
720
721         return 0;
722 }
723
724 int
725 writefiles(FILE *fp, const char *branch)
726 {
727         const git_oid *id;
728         git_tree *tree = NULL;
729         git_object *obj = NULL;
730         git_commit *commit = NULL;
731         int ret = -1;
732
733         fputs("<table id=\"files\"><thead>\n<tr>"
734               "<td>Mode</td><td>Name</td><td class=\"num\">Size</td>"
735               "</tr>\n</thead><tbody>\n", fp);
736
737         if (git_revparse_single(&obj, repo, branch))
738                 goto err;
739         id = git_object_id(obj);
740         if (git_commit_lookup(&commit, repo, id) ||
741             git_commit_tree(&tree, commit))
742                 goto err;
743         ret = writefilestree(fp, tree, branch, "");
744
745 err:
746         fputs("</tbody></table>", fp);
747
748         git_object_free(obj);
749         git_commit_free(commit);
750         git_tree_free(tree);
751
752         return ret;
753 }
754
755 int
756 refs_cmp(const void *v1, const void *v2)
757 {
758         git_reference *r1 = (*(git_reference **)v1);
759         git_reference *r2 = (*(git_reference **)v2);
760         int t1, t2;
761
762         t1 = git_reference_is_branch(r1);
763         t2 = git_reference_is_branch(r2);
764
765         if (t1 != t2)
766                 return t1 - t2;
767
768         return strcmp(git_reference_shorthand(r1),
769                       git_reference_shorthand(r2));
770 }
771
772 int
773 writerefs(FILE *fp)
774 {
775         struct commitinfo *ci;
776         const git_oid *id = NULL;
777         git_object *obj = NULL;
778         git_reference *dref = NULL, *r, *ref = NULL;
779         git_reference_iterator *it = NULL;
780         git_reference **refs = NULL;
781         size_t count, i, j, len, refcount = 0;
782         const char *cols[] = { "Branch", "Tag" }; /* first column title */
783         const char *titles[] = { "Branches", "Tags" };
784         const char *ids[] = { "branches", "tags" };
785         const char *name;
786
787         if (git_reference_iterator_new(&it, repo))
788                 return -1;
789
790         for (refcount = 0; !git_reference_next(&ref, it); refcount++) {
791                 if (!(refs = reallocarray(refs, refcount + 1, sizeof(git_reference *))))
792                         err(1, "realloc");
793                 refs[refcount] = ref;
794         }
795         git_reference_iterator_free(it);
796
797         /* sort by type then shorthand name */
798         qsort(refs, refcount, sizeof(git_reference *), refs_cmp);
799
800         for (j = 0; j < 2; j++) {
801                 for (i = 0, count = 0; i < refcount; i++) {
802                         if (!(git_reference_is_branch(refs[i]) && j == 0) &&
803                             !(git_reference_is_tag(refs[i]) && j == 1))
804                                 continue;
805
806                         switch (git_reference_type(refs[i])) {
807                         case GIT_REF_SYMBOLIC:
808                                 if (git_reference_resolve(&dref, refs[i]))
809                                         goto err;
810                                 r = dref;
811                                 break;
812                         case GIT_REF_OID:
813                                 r = refs[i];
814                                 break;
815                         default:
816                                 continue;
817                         }
818                         if (!(id = git_reference_target(r)))
819                                 goto err;
820                         if (git_reference_peel(&obj, r, GIT_OBJ_ANY))
821                                 goto err;
822                         if (!(id = git_object_id(obj)))
823                                 goto err;
824                         if (!(ci = commitinfo_getbyoid(id)))
825                                 break;
826
827                         /* print header if it has an entry (first). */
828                         if (++count == 1) {
829                                 fprintf(fp, "<h2>%s</h2><table id=\"%s\"><thead>\n<tr><td>%s</td>"
830                                       "<td>Age</td><td>Commit message</td>"
831                                       "<td>Author</td><td>Files</td><td class=\"num\">+</td>"
832                                       "<td class=\"num\">-</td></tr>\n</thead><tbody>\n",
833                                       titles[j], ids[j], cols[j]);
834                         }
835
836                         relpath = "";
837                         name = git_reference_shorthand(r);
838
839                         fputs("<tr><td>", fp);
840                         xmlencode(fp, name, strlen(name));
841                         fputs("</td><td>", fp);
842                         if (ci->author)
843                                 printtimeshort(fp, &(ci->author->when));
844                         fputs("</td><td>", fp);
845                         if (ci->summary) {
846                                 if (j)
847                                         fprintf(fp, "<a href=\"%scommit/%s.html\">",
848                                                 relpath, ci->oid);
849                                 if ((len = strlen(ci->summary)) > summarylen) {
850                                         xmlencode(fp, ci->summary, summarylen - 1);
851                                         fputs("…", fp);
852                                 } else {
853                                         xmlencode(fp, ci->summary, len);
854                                 }
855                                 if (j)
856                                         fputs("</a>", fp);
857                         }
858                         fputs("</td><td>", fp);
859                         if (ci->author)
860                                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
861                         fputs("</td><td class=\"num\">", fp);
862                         fprintf(fp, "%zu", ci->filecount);
863                         fputs("</td><td class=\"num\">", fp);
864                         fprintf(fp, "+%zu", ci->addcount);
865                         fputs("</td><td class=\"num\">", fp);
866                         fprintf(fp, "-%zu", ci->delcount);
867                         fputs("</td></tr>\n", fp);
868
869                         relpath = "../";
870
871                         commitinfo_free(ci);
872                         git_object_free(obj);
873                         obj = NULL;
874                         git_reference_free(dref);
875                         dref = NULL;
876                 }
877                 /* table footer */
878                 if (count)
879                         fputs("</tbody></table>", fp);
880         }
881
882 err:
883         git_object_free(obj);
884         git_reference_free(dref);
885
886         for (i = 0; i < refcount; i++)
887                 git_reference_free(refs[i]);
888         free(refs);
889
890         return 0;
891 }
892
893 int
894 main(int argc, char *argv[])
895 {
896         git_object *obj = NULL;
897         const git_error *e = NULL;
898         FILE *fp, *fpread;
899         char path[PATH_MAX], *p;
900         int status;
901
902         if (argc != 2) {
903                 fprintf(stderr, "%s <repodir>\n", argv[0]);
904                 return 1;
905         }
906         repodir = argv[1];
907
908         git_libgit2_init();
909
910         if ((status = git_repository_open_ext(&repo, repodir,
911                 GIT_REPOSITORY_OPEN_NO_SEARCH, NULL)) < 0) {
912                 e = giterr_last();
913                 fprintf(stderr, "error %d/%d: %s\n", status, e->klass, e->message);
914                 return status;
915         }
916
917         /* use directory name as name */
918         name = xbasename(repodir);
919
920         /* strip .git suffix */
921         if (!(stripped_name = strdup(name)))
922                 err(1, "strdup");
923         if ((p = strrchr(stripped_name, '.')))
924                 if (!strcmp(p, ".git"))
925                         *p = '\0';
926
927         /* read description or .git/description */
928         snprintf(path, sizeof(path), "%s%s%s",
929                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "description");
930         if (!(fpread = fopen(path, "r"))) {
931                 snprintf(path, sizeof(path), "%s%s%s",
932                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/description");
933                 fpread = fopen(path, "r");
934         }
935         if (fpread) {
936                 if (!fgets(description, sizeof(description), fpread))
937                         description[0] = '\0';
938                 fclose(fpread);
939         }
940
941         /* read url or .git/url */
942         snprintf(path, sizeof(path), "%s%s%s",
943                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "url");
944         if (!(fpread = fopen(path, "r"))) {
945                 snprintf(path, sizeof(path), "%s%s%s",
946                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/url");
947                 fpread = fopen(path, "r");
948         }
949         if (fpread) {
950                 if (!fgets(cloneurl, sizeof(cloneurl), fpread))
951                         cloneurl[0] = '\0';
952                 cloneurl[strcspn(cloneurl, "\n")] = '\0';
953                 fclose(fpread);
954         }
955
956         /* check LICENSE */
957         haslicense = !git_revparse_single(&obj, repo, "HEAD:LICENSE");
958         git_object_free(obj);
959         /* check README */
960         hasreadme = !git_revparse_single(&obj, repo, "HEAD:README");
961         git_object_free(obj);
962
963         /* log for HEAD */
964         fp = efopen("log.html", "w");
965         relpath = "";
966         writeheader(fp);
967         writelog(fp, "HEAD");
968         writefooter(fp);
969         fclose(fp);
970
971         /* files for HEAD */
972         fp = efopen("files.html", "w");
973         writeheader(fp);
974         writefiles(fp, "HEAD");
975         writefooter(fp);
976         fclose(fp);
977
978         /* summary page with branches and tags */
979         fp = efopen("refs.html", "w");
980         writeheader(fp);
981         writerefs(fp);
982         writefooter(fp);
983         fclose(fp);
984
985         /* Atom feed */
986         fp = efopen("atom.xml", "w");
987         writeatom(fp);
988         fclose(fp);
989
990         /* cleanup */
991         git_repository_free(repo);
992         git_libgit2_shutdown();
993
994         return 0;
995 }