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