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