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