]> git.armaanb.net Git - stagit.git/blob - stagit.c
Rename “Age” column headers into “Date”
[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         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</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 int
286 writeblobhtml(FILE *fp, const git_blob *blob)
287 {
288         off_t i;
289         size_t n = 0;
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                 n++;
298                 fprintf(fp, nfmt, n, n, n);
299                 for (i = 0; i < len - 1; i++) {
300                         if (s[i] == '\n') {
301                                 n++;
302                                 fprintf(fp, nfmt, n, n, n);
303                         }
304                 }
305         }
306
307         fputs("</pre></td><td><pre>\n", fp);
308         xmlencode(fp, s, (size_t)len);
309         fputs("</pre></td></tr></table>\n", fp);
310
311         return n;
312 }
313
314 void
315 printcommit(FILE *fp, struct commitinfo *ci)
316 {
317         fprintf(fp, "<b>commit</b> <a href=\"%scommit/%s.html\">%s</a>\n",
318                 relpath, ci->oid, ci->oid);
319
320         if (ci->parentoid[0])
321                 fprintf(fp, "<b>parent</b> <a href=\"%scommit/%s.html\">%s</a>\n",
322                         relpath, ci->parentoid, ci->parentoid);
323
324         if (ci->author) {
325                 fputs("<b>Author:</b> ", fp);
326                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
327                 fputs(" &lt;<a href=\"mailto:", fp);
328                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
329                 fputs("\">", fp);
330                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
331                 fputs("</a>&gt;\n<b>Date:</b>   ", fp);
332                 printtime(fp, &(ci->author->when));
333                 fputc('\n', fp);
334         }
335         if (ci->msg) {
336                 fputc('\n', fp);
337                 xmlencode(fp, ci->msg, strlen(ci->msg));
338                 fputc('\n', fp);
339         }
340 }
341
342 void
343 printshowfile(struct commitinfo *ci)
344 {
345         const git_diff_delta *delta;
346         const git_diff_hunk *hunk;
347         const git_diff_line *line;
348         git_patch *patch;
349         git_buf statsbuf;
350         size_t ndeltas, nhunks, nhunklines;
351         FILE *fp;
352         size_t i, j, k;
353         char path[PATH_MAX];
354
355         snprintf(path, sizeof(path), "commit/%s.html", ci->oid);
356         /* check if file exists if so skip it */
357         if (!access(path, F_OK))
358                 return;
359
360         fp = efopen(path, "w");
361         writeheader(fp);
362         fputs("<pre>", fp);
363         printcommit(fp, ci);
364
365         memset(&statsbuf, 0, sizeof(statsbuf));
366
367         /* diff stat */
368         if (ci->stats &&
369             !git_diff_stats_to_buf(&statsbuf, ci->stats,
370                                    GIT_DIFF_STATS_FULL | GIT_DIFF_STATS_SHORT, 80)) {
371                 if (statsbuf.ptr && statsbuf.ptr[0]) {
372                         fputs("<b>Diffstat:</b>\n", fp);
373                         xmlencode(fp, statsbuf.ptr, strlen(statsbuf.ptr));
374                 }
375         }
376
377         fputs("<hr/>", fp);
378
379         ndeltas = git_diff_num_deltas(ci->diff);
380         for (i = 0; i < ndeltas; i++) {
381                 if (git_patch_from_diff(&patch, ci->diff, i)) {
382                         git_patch_free(patch);
383                         break;
384                 }
385
386                 delta = git_patch_get_delta(patch);
387                 fprintf(fp, "<b>diff --git a/<a href=\"%sfile/%s.html\">%s</a> b/<a href=\"%sfile/%s.html\">%s</a></b>\n",
388                         relpath, delta->old_file.path, delta->old_file.path,
389                         relpath, delta->new_file.path, delta->new_file.path);
390
391                 /* check binary data */
392                 if (delta->flags & GIT_DIFF_FLAG_BINARY) {
393                         fputs("Binary files differ\n", fp);
394                         git_patch_free(patch);
395                         continue;
396                 }
397
398                 nhunks = git_patch_num_hunks(patch);
399                 for (j = 0; j < nhunks; j++) {
400                         if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
401                                 break;
402
403                         fprintf(fp, "<a href=\"#h%zu\" id=\"h%zu\" class=\"h\">", j, j);
404                         xmlencode(fp, hunk->header, hunk->header_len);
405                         fputs("</a>", fp);
406
407                         for (k = 0; ; k++) {
408                                 if (git_patch_get_line_in_hunk(&line, patch, j, k))
409                                         break;
410                                 if (line->old_lineno == -1)
411                                         fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"i\">+",
412                                                 j, k, j, k);
413                                 else if (line->new_lineno == -1)
414                                         fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"d\">-",
415                                                 j, k, j, k);
416                                 else
417                                         fputc(' ', fp);
418                                 xmlencode(fp, line->content, line->content_len);
419                                 if (line->old_lineno == -1 || line->new_lineno == -1)
420                                         fputs("</a>", fp);
421                         }
422                 }
423                 git_patch_free(patch);
424         }
425         git_buf_free(&statsbuf);
426
427         fputs("</pre>\n", fp);
428         writefooter(fp);
429         fclose(fp);
430         return;
431 }
432
433 int
434 writelog(FILE *fp, const git_oid *oid)
435 {
436         struct commitinfo *ci;
437         git_revwalk *w = NULL;
438         git_oid id;
439         size_t len;
440
441         git_revwalk_new(&w, repo);
442         git_revwalk_push(w, oid);
443         git_revwalk_sorting(w, GIT_SORT_TIME);
444         git_revwalk_simplify_first_parent(w);
445
446         fputs("<table id=\"log\"><thead>\n<tr><td>Date</td><td>Commit message</td>"
447                   "<td>Author</td><td>Files</td><td class=\"num\">+</td>"
448                   "<td class=\"num\">-</td></tr>\n</thead><tbody>\n", fp);
449
450         while (!git_revwalk_next(&id, w)) {
451                 relpath = "";
452
453                 if (!(ci = commitinfo_getbyoid(&id)))
454                         break;
455
456                 fputs("<tr><td>", fp);
457                 if (ci->author)
458                         printtimeshort(fp, &(ci->author->when));
459                 fputs("</td><td>", fp);
460                 if (ci->summary) {
461                         fprintf(fp, "<a href=\"%scommit/%s.html\">", relpath, ci->oid);
462                         if ((len = strlen(ci->summary)) > summarylen) {
463                                 xmlencode(fp, ci->summary, summarylen - 1);
464                                 fputs("…", fp);
465                         } else {
466                                 xmlencode(fp, ci->summary, len);
467                         }
468                         fputs("</a>", fp);
469                 }
470                 fputs("</td><td>", fp);
471                 if (ci->author)
472                         xmlencode(fp, ci->author->name, strlen(ci->author->name));
473                 fputs("</td><td class=\"num\">", fp);
474                 fprintf(fp, "%zu", ci->filecount);
475                 fputs("</td><td class=\"num\">", fp);
476                 fprintf(fp, "+%zu", ci->addcount);
477                 fputs("</td><td class=\"num\">", fp);
478                 fprintf(fp, "-%zu", ci->delcount);
479                 fputs("</td></tr>\n", fp);
480
481                 relpath = "../";
482                 printshowfile(ci);
483
484                 commitinfo_free(ci);
485         }
486         fputs("</tbody></table>", fp);
487
488         git_revwalk_free(w);
489
490         relpath = "";
491
492         return 0;
493 }
494
495 void
496 printcommitatom(FILE *fp, struct commitinfo *ci)
497 {
498         fputs("<entry>\n", fp);
499
500         fprintf(fp, "<id>%s</id>\n", ci->oid);
501         if (ci->author) {
502                 fputs("<updated>", fp);
503                 printtimez(fp, &(ci->author->when));
504                 fputs("</updated>\n", fp);
505         }
506         if (ci->summary) {
507                 fputs("<title type=\"text\">", fp);
508                 xmlencode(fp, ci->summary, strlen(ci->summary));
509                 fputs("</title>\n", fp);
510         }
511
512         fputs("<content type=\"text\">", fp);
513         fprintf(fp, "commit %s\n", ci->oid);
514         if (ci->parentoid[0])
515                 fprintf(fp, "parent %s\n", ci->parentoid);
516         if (ci->author) {
517                 fputs("Author: ", fp);
518                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
519                 fputs(" &lt;", fp);
520                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
521                 fputs("&gt;\nDate:   ", fp);
522                 printtime(fp, &(ci->author->when));
523                 fputc('\n', fp);
524         }
525         if (ci->msg) {
526                 fputc('\n', fp);
527                 xmlencode(fp, ci->msg, strlen(ci->msg));
528         }
529         fputs("\n</content>\n", fp);
530         if (ci->author) {
531                 fputs("<author><name>", fp);
532                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
533                 fputs("</name>\n<email>", fp);
534                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
535                 fputs("</email>\n</author>\n", fp);
536         }
537         fputs("</entry>\n", fp);
538 }
539
540 int
541 writeatom(FILE *fp)
542 {
543         struct commitinfo *ci;
544         git_revwalk *w = NULL;
545         git_oid id;
546         size_t i, m = 100; /* max */
547
548         fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
549               "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n<title>", fp);
550         xmlencode(fp, stripped_name, strlen(stripped_name));
551         fputs(", branch HEAD</title>\n<subtitle>", fp);
552         xmlencode(fp, description, strlen(description));
553         fputs("</subtitle>\n", fp);
554
555         git_revwalk_new(&w, repo);
556         git_revwalk_push_head(w);
557         git_revwalk_sorting(w, GIT_SORT_TIME);
558         git_revwalk_simplify_first_parent(w);
559
560         for (i = 0; i < m && !git_revwalk_next(&id, w); i++) {
561                 if (!(ci = commitinfo_getbyoid(&id)))
562                         break;
563                 printcommitatom(fp, ci);
564                 commitinfo_free(ci);
565         }
566         git_revwalk_free(w);
567
568         fputs("</feed>", fp);
569
570         return 0;
571 }
572
573 int
574 writeblob(git_object *obj, const char *fpath, const char *filename, git_off_t filesize)
575 {
576         char tmp[PATH_MAX] = "";
577         char *d;
578         const char *p;
579         int lc = 0;
580         FILE *fp;
581
582         d = xdirname(fpath);
583         if (mkdirp(d)) {
584                 free(d);
585                 return -1;
586         }
587         free(d);
588
589         p = fpath;
590         while (*p) {
591                 if (*p == '/')
592                         strlcat(tmp, "../", sizeof(tmp));
593                 p++;
594         }
595         relpath = tmp;
596
597         fp = efopen(fpath, "w");
598         writeheader(fp);
599         fputs("<p> ", fp);
600         xmlencode(fp, filename, strlen(filename));
601         fprintf(fp, " (%juB)", (uintmax_t)filesize);
602         fputs("</p><hr/>", fp);
603
604         if (git_blob_is_binary((git_blob *)obj)) {
605                 fputs("<p>Binary file</p>\n", fp);
606         } else {
607                 lc = writeblobhtml(fp, (git_blob *)obj);
608                 if (ferror(fp))
609                         err(1, "fwrite");
610         }
611         writefooter(fp);
612         fclose(fp);
613
614         relpath = "";
615
616         return lc;
617 }
618
619 const char *
620 filemode(git_filemode_t m)
621 {
622         static char mode[11];
623
624         memset(mode, '-', sizeof(mode) - 1);
625         mode[10] = '\0';
626
627         if (S_ISREG(m))
628                 mode[0] = '-';
629         else if (S_ISBLK(m))
630                 mode[0] = 'b';
631         else if (S_ISCHR(m))
632                 mode[0] = 'c';
633         else if (S_ISDIR(m))
634                 mode[0] = 'd';
635         else if (S_ISFIFO(m))
636                 mode[0] = 'p';
637         else if (S_ISLNK(m))
638                 mode[0] = 'l';
639         else if (S_ISSOCK(m))
640                 mode[0] = 's';
641         else
642                 mode[0] = '?';
643
644         if (m & S_IRUSR) mode[1] = 'r';
645         if (m & S_IWUSR) mode[2] = 'w';
646         if (m & S_IXUSR) mode[3] = 'x';
647         if (m & S_IRGRP) mode[4] = 'r';
648         if (m & S_IWGRP) mode[5] = 'w';
649         if (m & S_IXGRP) mode[6] = 'x';
650         if (m & S_IROTH) mode[7] = 'r';
651         if (m & S_IWOTH) mode[8] = 'w';
652         if (m & S_IXOTH) mode[9] = 'x';
653
654         if (m & S_ISUID) mode[3] = (mode[3] == 'x') ? 's' : 'S';
655         if (m & S_ISGID) mode[6] = (mode[6] == 'x') ? 's' : 'S';
656         if (m & S_ISVTX) mode[9] = (mode[9] == 'x') ? 't' : 'T';
657
658         return mode;
659 }
660
661 int
662 writefilestree(FILE *fp, git_tree *tree, const char *branch, const char *path)
663 {
664         const git_tree_entry *entry = NULL;
665         const char *entryname;
666         char filepath[PATH_MAX], entrypath[PATH_MAX];
667         git_object *obj = NULL;
668         git_off_t filesize;
669         size_t count, i;
670         int lc, ret;
671
672         count = git_tree_entrycount(tree);
673         for (i = 0; i < count; i++) {
674                 if (!(entry = git_tree_entry_byindex(tree, i)) ||
675                     git_tree_entry_to_object(&obj, repo, entry))
676                         return -1;
677                 entryname = git_tree_entry_name(entry);
678                 snprintf(entrypath, sizeof(entrypath), "%s%s%s",
679                          path, path[0] ? "/" : "", entryname);
680                 switch (git_object_type(obj)) {
681                 case GIT_OBJ_BLOB:
682                         break;
683                 case GIT_OBJ_TREE:
684                         /* NOTE: recurses */
685                         ret = writefilestree(fp, (git_tree *)obj, branch,
686                                              entrypath);
687                         git_object_free(obj);
688                         if (ret)
689                                 return ret;
690                         continue;
691                 default:
692                         git_object_free(obj);
693                         continue;
694                 }
695                 if (path[0])
696                         snprintf(filepath, sizeof(filepath), "file/%s/%s.html",
697                                  path, entryname);
698                 else
699                         snprintf(filepath, sizeof(filepath), "file/%s.html",
700                                  entryname);
701                 filesize = git_blob_rawsize((git_blob *)obj);
702
703                 lc = writeblob(obj, filepath, entryname, filesize);
704
705                 fputs("<tr><td>", fp);
706                 fputs(filemode(git_tree_entry_filemode(entry)), fp);
707                 fprintf(fp, "</td><td><a href=\"%s%s\">", relpath, filepath);
708                 xmlencode(fp, entrypath, strlen(entrypath));
709                 fputs("</a></td><td class=\"num\">", fp);
710                 if (showlinecount && lc > 0)
711                         fprintf(fp, "%dL", lc);
712                 else
713                         fprintf(fp, "%juB", (uintmax_t)filesize);
714                 fputs("</td></tr>\n", fp);
715         }
716
717         return 0;
718 }
719
720 int
721 writefiles(FILE *fp, const git_oid *id, const char *branch)
722 {
723         git_tree *tree = NULL;
724         git_commit *commit = NULL;
725         int ret = -1;
726
727         fputs("<table id=\"files\"><thead>\n<tr>"
728               "<td>Mode</td><td>Name</td><td class=\"num\">Size</td>"
729               "</tr>\n</thead><tbody>\n", fp);
730
731         if (git_commit_lookup(&commit, repo, id) ||
732             git_commit_tree(&tree, commit))
733                 goto err;
734         ret = writefilestree(fp, tree, branch, "");
735
736 err:
737         fputs("</tbody></table>", fp);
738
739         git_commit_free(commit);
740         git_tree_free(tree);
741
742         return ret;
743 }
744
745 int
746 refs_cmp(const void *v1, const void *v2)
747 {
748         git_reference *r1 = (*(git_reference **)v1);
749         git_reference *r2 = (*(git_reference **)v2);
750         int t1, t2;
751
752         t1 = git_reference_is_branch(r1);
753         t2 = git_reference_is_branch(r2);
754
755         if (t1 != t2)
756                 return t1 - t2;
757
758         return strcmp(git_reference_shorthand(r1),
759                       git_reference_shorthand(r2));
760 }
761
762 int
763 writerefs(FILE *fp)
764 {
765         struct commitinfo *ci;
766         const git_oid *id = NULL;
767         git_object *obj = NULL;
768         git_reference *dref = NULL, *r, *ref = NULL;
769         git_reference_iterator *it = NULL;
770         git_reference **refs = NULL;
771         size_t count, i, j, refcount = 0;
772         const char *cols[] = { "Branch", "Tag" }; /* first column title */
773         const char *titles[] = { "Branches", "Tags" };
774         const char *ids[] = { "branches", "tags" };
775         const char *name;
776
777         if (git_reference_iterator_new(&it, repo))
778                 return -1;
779
780         for (refcount = 0; !git_reference_next(&ref, it); refcount++) {
781                 if (!(refs = reallocarray(refs, refcount + 1, sizeof(git_reference *))))
782                         err(1, "realloc");
783                 refs[refcount] = ref;
784         }
785         git_reference_iterator_free(it);
786
787         /* sort by type then shorthand name */
788         qsort(refs, refcount, sizeof(git_reference *), refs_cmp);
789
790         for (j = 0; j < 2; j++) {
791                 for (i = 0, count = 0; i < refcount; i++) {
792                         if (!(git_reference_is_branch(refs[i]) && j == 0) &&
793                             !(git_reference_is_tag(refs[i]) && j == 1))
794                                 continue;
795
796                         switch (git_reference_type(refs[i])) {
797                         case GIT_REF_SYMBOLIC:
798                                 if (git_reference_resolve(&dref, refs[i]))
799                                         goto err;
800                                 r = dref;
801                                 break;
802                         case GIT_REF_OID:
803                                 r = refs[i];
804                                 break;
805                         default:
806                                 continue;
807                         }
808                         if (!(id = git_reference_target(r)))
809                                 goto err;
810                         if (git_reference_peel(&obj, r, GIT_OBJ_ANY))
811                                 goto err;
812                         if (!(id = git_object_id(obj)))
813                                 goto err;
814                         if (!(ci = commitinfo_getbyoid(id)))
815                                 break;
816
817                         /* print header if it has an entry (first). */
818                         if (++count == 1) {
819                                 fprintf(fp, "<h2>%s</h2><table id=\"%s\"><thead>\n<tr><td>%s</td>"
820                                       "<td>Last commit date</td><td>Author</td>\n</tr>\n</thead><tbody>\n",
821                                       titles[j], ids[j], cols[j]);
822                         }
823
824                         relpath = "";
825                         name = git_reference_shorthand(r);
826
827                         fputs("<tr><td>", fp);
828                         xmlencode(fp, name, strlen(name));
829                         fputs("</td><td>", fp);
830                         if (ci->author)
831                                 printtimeshort(fp, &(ci->author->when));
832                         fputs("</td><td>", fp);
833                         if (ci->author)
834                                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
835                         fputs("</td></tr>\n", fp);
836
837                         relpath = "../";
838
839                         commitinfo_free(ci);
840                         git_object_free(obj);
841                         obj = NULL;
842                         git_reference_free(dref);
843                         dref = NULL;
844                 }
845                 /* table footer */
846                 if (count)
847                         fputs("</tbody></table><br/>", fp);
848         }
849
850 err:
851         git_object_free(obj);
852         git_reference_free(dref);
853
854         for (i = 0; i < refcount; i++)
855                 git_reference_free(refs[i]);
856         free(refs);
857
858         return 0;
859 }
860
861 int
862 main(int argc, char *argv[])
863 {
864         git_object *obj = NULL;
865         const git_oid *head = NULL;
866         const git_error *e = NULL;
867         FILE *fp, *fpread;
868         char path[PATH_MAX], *p;
869         int status;
870
871         if (argc != 2) {
872                 fprintf(stderr, "%s <repodir>\n", argv[0]);
873                 return 1;
874         }
875         repodir = argv[1];
876
877         git_libgit2_init();
878
879         if ((status = git_repository_open_ext(&repo, repodir,
880                 GIT_REPOSITORY_OPEN_NO_SEARCH, NULL)) < 0) {
881                 e = giterr_last();
882                 fprintf(stderr, "error %d/%d: %s\n", status, e->klass, e->message);
883                 return status;
884         }
885
886         /* find HEAD */
887         if (git_revparse_single(&obj, repo, "HEAD"))
888                 return 1;
889         head = git_object_id(obj);
890         git_object_free(obj);
891
892         /* use directory name as name */
893         name = xbasename(repodir);
894
895         /* strip .git suffix */
896         if (!(stripped_name = strdup(name)))
897                 err(1, "strdup");
898         if ((p = strrchr(stripped_name, '.')))
899                 if (!strcmp(p, ".git"))
900                         *p = '\0';
901
902         /* read description or .git/description */
903         snprintf(path, sizeof(path), "%s%s%s",
904                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "description");
905         if (!(fpread = fopen(path, "r"))) {
906                 snprintf(path, sizeof(path), "%s%s%s",
907                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/description");
908                 fpread = fopen(path, "r");
909         }
910         if (fpread) {
911                 if (!fgets(description, sizeof(description), fpread))
912                         description[0] = '\0';
913                 fclose(fpread);
914         }
915
916         /* read url or .git/url */
917         snprintf(path, sizeof(path), "%s%s%s",
918                 repodir, repodir[strlen(repodir)] == '/' ? "" : "/", "url");
919         if (!(fpread = fopen(path, "r"))) {
920                 snprintf(path, sizeof(path), "%s%s%s",
921                         repodir, repodir[strlen(repodir)] == '/' ? "" : "/", ".git/url");
922                 fpread = fopen(path, "r");
923         }
924         if (fpread) {
925                 if (!fgets(cloneurl, sizeof(cloneurl), fpread))
926                         cloneurl[0] = '\0';
927                 cloneurl[strcspn(cloneurl, "\n")] = '\0';
928                 fclose(fpread);
929         }
930
931         /* check LICENSE */
932         haslicense = !git_revparse_single(&obj, repo, "HEAD:LICENSE");
933         git_object_free(obj);
934         /* check README */
935         hasreadme = !git_revparse_single(&obj, repo, "HEAD:README");
936         git_object_free(obj);
937
938         /* log for HEAD */
939         fp = efopen("log.html", "w");
940         relpath = "";
941         writeheader(fp);
942         mkdir("commit", 0755);
943         writelog(fp, head);
944         writefooter(fp);
945         fclose(fp);
946
947         /* files for HEAD */
948         fp = efopen("files.html", "w");
949         writeheader(fp);
950         writefiles(fp, head, "HEAD");
951         writefooter(fp);
952         fclose(fp);
953
954         /* summary page with branches and tags */
955         fp = efopen("refs.html", "w");
956         writeheader(fp);
957         writerefs(fp);
958         writefooter(fp);
959         fclose(fp);
960
961         /* Atom feed */
962         fp = efopen("atom.xml", "w");
963         writeatom(fp);
964         fclose(fp);
965
966         /* cleanup */
967         git_repository_free(repo);
968         git_libgit2_shutdown();
969
970         return 0;
971 }