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