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